文档菜单
文档首页
/ / /
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集合中执行操作

  • 匹配名称为"Cafe Tomato"的文档并替换为新文档

  • 匹配名称为"Cafe Zucchini"的文档并将值更新为"Zucchini Land"

coll := client.Database("sample_restaurants").Collection("restaurants")
// Creates write models that specify replace and update operations
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"}}}}),
}
// Specifies that the bulk write is ordered
opts := options.BulkWrite().SetOrdered(true)
// Runs a bulk write operation for the specified write operations
results, err := coll.BulkWrite(context.TODO(), models, opts)

查看一个可运行的完整示例

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

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

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

要了解如何在集合上执行批量写入操作并处理潜在的错误,请参阅批量操作。

返回

删除多个