文档菜单
文档首页
/ / /
Go 驱动
/ /

替换文档

您可以使用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"
}

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

要了解更多关于替换文档、指定查询过滤器以及处理潜在错误的信息,请参阅修改文档。

ReplaceOne()

返回

更新多个