Docs 菜单

Docs 主页开发应用程序MongoDB 驱动程序Go 驱动程序

更新多个文档

可以使用 UpdateMany() 方法更新集合中的多个文档。

提示

参阅“使用示例”,了解如何运行此示例。

以下示例对 listingsAndReviews 集合执行以下操作:

  • 匹配地址子文档的市场字段(address.market 为“Sydney”)的文档

  • 将匹配文档的 price 更新 1.15 倍

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()

← 更新文档