可以使用 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")
// Creates write models that specify replace and update operationsmodels := []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 orderedopts := options.BulkWrite().SetOrdered(true)
// Runs a bulk write operation for the specified write operationsresults, err := coll.BulkWrite(context.TODO(), models, opts)查看完全可运行的示例
预期结果
运行完整示例后,可以在 restaurants 集合中找到以下文档:
{ "_id": ObjectId("..."), "name": "Zucchini Land", "cuisine": "French"}有关如何查找文档的示例,请参阅查找文档。
更多信息
要了解有关对集合执行批量写入操作和处理潜在错误的更多信息,请参阅批量操作。