Docs 菜单
Docs 主页
/ / /
Go
/

执行批量操作

您可以使用 BulkWrite() 方法对集合执行批量写入操作。

提示

阅读用法示例,了解如何运行此示例。

此示例使用以下 Restaurant 结构作为 restaurants 集合中文档的模型:

type Restaurant struct {
Name string
RestaurantId string `bson:"restaurant_id,omitempty"`
Cuisine string `bson:"cuisine,omitempty"`
Address interface{} `bson:"address,omitempty"`
Borough string `bson:"borough,omitempty"`
Grades []interface{} `bson:"grades,omitempty"`
}

omitempty 结构体标签留空时会省略插入文档中的相应字段。

以下示例按顺序对 restaurants 集合执行以下操作:

  • 匹配 name 为“Cafe Tomato”的文档,并将其替换为新文档

  • 匹配 name 为“Cafe Zucchini”的文档,并将值更新为“Zucchini Land”

coll := client.Database("sample_restaurants").Collection("restaurants")
models := []mongo.WriteModel{
mongo.NewReplaceOneModel().SetFilter(bson.D{{"name", "Cafe Tomato"}}).
SetReplacement(Restaurant{Name: "Cafe Zucchini", Cuisine: "French"}),
mongo.NewUpdateOneModel().SetFilter(bson.D{{"name", "Cafe Zucchini"}}).
SetUpdate(bson.D{{"$set", bson.D{{"name", "Zucchini Land"}}}}),
}
opts := options.BulkWrite().SetOrdered(true)
results, err := coll.BulkWrite(context.TODO(), models, opts)

查看 完全可运行的示例

运行完整示例后,可以在 restaurants 集合中找到以下文档:

{
"_id": ObjectId("..."),
"name": "Zucchini Land",
"cuisine": "French"
}

有关如何查找文档的示例,请参阅查找文档

要了解有关对集合执行批量写入操作和处理潜在错误的更多信息,请参阅批量操作

后退

删除多个文档

来年

监控数据变化