对于您的用例,您将使用collection.BulkWrite
. 您可以在存储库的示例目录中找到如何使用go-mongo-driver
的示例。
collection.UpdateMany()
将使用相同的更新过滤器和修改更新集合中的多个文档。在 mongo shell 等效的文档中有更多文档。例子:
result, err := coll.UpdateMany(
context.Background(),
bson.NewDocument(
bson.EC.SubDocumentFromElements("qty",
bson.EC.Int32("$lt", 50),
),
),
bson.NewDocument(
bson.EC.SubDocumentFromElements("$set",
bson.EC.String("size.uom", "cm"),
bson.EC.String("status", "P"),
),
bson.EC.SubDocumentFromElements("$currentDate",
bson.EC.Boolean("lastModified", true),
),
),
)
collection.BulkWrite()
将执行一组批量写入操作。BulkWrite API 仅在几天前为 go 驱动程序引入。示例很少,但是您始终可以检查测试文件。例子:
var operations []mongo.WriteModel
operation := mongo.NewUpdateOneModel()
operation.Filter(bson.NewDocument(
bson.EC.SubDocumentFromElements("qty",
bson.EC.Int32("$lt", 50),
),
))
operation.Update(bson.NewDocument(
bson.EC.SubDocumentFromElements("$set",
bson.EC.String("size.uom", "cm"),
bson.EC.String("status", "P"),
),
bson.EC.SubDocumentFromElements("$currentDate",
bson.EC.Boolean("lastModified", true),
),
))
operations = append(operations, operation)
result, err := coll.BulkWrite(
context.Background(),
operations,
)