对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

替换文档

您可以使用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 集合执行以下操作:

  • 匹配文档中 name 为“Madame Vo”的文档

  • 用新文档替换匹配的文档

coll := client.Database("sample_restaurants").Collection("restaurants")filter := bson.D{{"name", "Madame Vo"}} // Creates a new document containing "Name" and "Cuisine" fieldsreplacement := Restaurant{Name: "Monsieur Vo", Cuisine: "Asian Fusion"} // Replaces the first document that matches the filter with a new documentresult, err := coll.ReplaceOne(context.TODO(), filter, replacement)if err != nil { panic(err)}

查看完全可运行的示例

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

{ "_id" : ObjectId("..."), "name" : "Monsieur Vo", "cuisine" : "Asian Fusion"}

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

要了解有关替换文档、指定查询筛选器和处理潜在错误的更多信息,请参阅修改文档。

replaceOne()

给本页内容打分