替换文档
您可以使用ReplaceOne()
方法在集合中替换文档。
示例
提示
阅读使用示例了解如何运行此示例。
此示例使用以下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
集合执行以下操作
匹配名称为"Madame Vo"的文档
将匹配的文档替换为新文档
coll := client.Database("sample_restaurants").Collection("restaurants") filter := bson.D{{"name", "Madame Vo"}} // Creates a new document containing "Name" and "Cuisine" fields replacement := Restaurant{Name: "Monsieur Vo", Cuisine: "Asian Fusion"} // Replaces the first document that matches the filter with a new document result, err := coll.ReplaceOne(context.TODO(), filter, replacement) if err != nil { panic(err) }
查看一个可运行的完整示例
预期结果
运行完整示例后,您可以在restaurants
集合中找到以下替换后的文档
{ "_id" : ObjectId("..."), "name" : "Monsieur Vo", "cuisine" : "Asian Fusion" }
有关如何查找文档的示例,请参阅查找文档使用示例。
更多信息
要了解更多关于替换文档、指定查询过滤器以及处理潜在错误的信息,请参阅修改文档。