6

我正在从 mgo 驱动程序迁移,我的函数如下所示:

queue := collection.Bulk()
for j := range changes {
    ..
    queue.Update(doc, update)
}
saveResult, err := queue.Run()

这会在循环中对单个文档进行一些$push和更新。$set我应该如何使用官方驱动程序执行此操作?是collection.BulkWrite()还是collection.UpdateMany()?文档是如此模糊,我不知道如何使用它们以及它们有什么区别。任何帮助,将不胜感激。

4

1 回答 1

10

对于您的用例,您将使用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,
)
于 2018-10-28T09:08:39.837 回答