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

更新多个文档

您可以通过使用UpdateMany() 方法来在集合中更新多个文档。

提示

阅读使用示例了解如何运行此示例。

以下示例在listingsAndReviews集合上执行以下操作

  • 匹配地址子文档的市场字段address.market为"Sydney"的文档

  • 通过1.15倍更新匹配文档中的price

coll := client.Database("sample_airbnb").Collection("listingsAndReviews")
filter := bson.D{{"address.market", "Sydney"}}
// Creates instructions to update the values of the "price" field
update := bson.D{{"$mul", bson.D{{"price", 1.15}}}}
// Updates documents in which the value of the "address.market"
// field is "Sydney"
result, err := coll.UpdateMany(context.TODO(), filter, update)
if err != nil {
panic(err)
}

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

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

// results truncated
...
{ "_id" : "10091713", ... , "name" : "Surry Hills Studio", ... , "price" : 181.00, ... },
{ "_id" : "9908871", ... , "name" : "Family friendly beach house", ... , "price" : 751.00, ... },
{ "_id" : "20989061", ... , "name" : "Big and sunny Narraben room", ... , "price" : 60.00, ... },
...

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

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

要了解有关更新操作符的更多信息,请参阅MongoDB更新操作符参考文档。

UpdateMany()

返回

更新单个文档