文档菜单
文档首页
/ / /
Go 驱动
/ / /

单次操作插入或更新

本页内容

  • 概述
  • 更新/插入
  • 更多信息

在本指南中,您可以学习如何执行更新插入(upsert).

本指南中的示例使用了以下Plant 结构作为 plants 集合中文档的模型

type Plant struct {
Species string
PlantID int32 `bson:"plant_id"`
Height float64
}

要运行本指南中的示例,请使用以下片段将样本数据加载到 db.plants 集合中

coll := client.Database("db").Collection("plants")
docs := []interface{}{
Plant{Species: "Polyscias fruticosa", PlantID: 1, Height: 27.6},
Plant{Species: "Polyscias fruticosa", PlantID: 2, Height: 34.9},
Plant{Species: "Ledebouria socialis", PlantID: 1, Height: 11.4},
}
result, err := coll.InsertMany(context.TODO(), docs)

每个文档都包含一个关于单个植物的描述,该描述包括物种、植物 ID 和对应于每个文档中的 speciesplant_idheight 字段的物种、植物 ID 和高度。

提示

不存在的数据库和集合

如果您在执行写操作时所需的数据库和集合不存在,服务器会隐式创建它们。

应用程序使用插入和更新操作来存储和修改数据。有时,您必须根据文档是否存在来选择插入或更新操作。MongoDB 通过 更新插入(upsert) 选项简化了我们的决策。

更新插入(upsert)执行以下操作之一

  • 更新与您的查询过滤器匹配的文档

  • 如果没有查询过滤器匹配,则插入新文档

您可以通过在以下写操作方法的选项中传递 true 来指定 upsert 操作

  • UpdateOne()

  • UpdateByID()

  • UpdateMany()

  • ReplaceOne()

  • FindOneAndUpdate()

  • FindOneAndReplace()

提示

如果您没有指定 upsert,则在查询过滤器匹配零文档时,写操作不会发生任何变化。这相当于在 SetUpsert() 方法中传递 false

以下示例执行以下操作

  • 匹配 species 为 "Ledebouria socialis" 且 plant_id3 的文档

  • 将匹配文档的 height 更新为 8.3

  • 如果没有匹配查询过滤器,则插入此文档

filter := bson.D{{"species", "Ledebouria socialis"}, {"plant_id", 3}}
update := bson.D{{"$set", bson.D{{"species", "Ledebouria socialis"}, {"plant_id", 3}, {"height", 8.3}}}}
opts := options.Update().SetUpsert(true)
result, err := coll.UpdateOne(context.TODO(), filter, update, opts)
if err != nil {
panic(err)
}
fmt.Printf("Number of documents updated: %v\n", result.ModifiedCount)
fmt.Printf("Number of documents upserted: %v\n", result.UpsertedCount)
Number of documents updated: 0
Number of documents upserted: 1

如果您查询 plants 集合以查看所有文档,您将看到由于查询过滤器未匹配任何文档,因此插入了一个具有指定字段的新文档

{"species":"Polyscias fruticosa","plant_id":1,"height":27.6}
{"species":"Polyscias fruticosa","plant_id":2,"height":34.9}
{"species":"Ledebouria socialis","plant_id":1,"height":11.4}
{"species":"Ledebouria socialis","plant_id":3,"height":8.3}

有关所述操作的更多信息,请参阅以下指南

  • 指定查询

  • 修改文档

  • 复合操作

要了解更多关于本指南中提到的任何方法或类型,请参阅以下 API 文档

返回

更新