dqg17080 2018-10-27 08:05 采纳率: 0%
浏览 736
已采纳

如何使用MongoDB的Go驱动程序BulkWrite \ UpdateMany

I'm migrating from mgo driver, and my function looks like this:

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

This makes some $push and $set updates to a single document in a loop. How should I do this with the official driver ? Is it collection.BulkWrite() or collection.UpdateMany() ? Documentation is so vague, I'm lost on how use them both and what's the difference. Any help would be appreciated.

  • 写回答

1条回答 默认 最新

  • dongsi5381 2018-10-28 09:08
    关注

    For your use case, you would use collection.BulkWrite. You can find examples of how to use go-mongo-driver in the examples directory of the repository.

    collection.UpdateMany() will update multiple documents in the collection using the same update filter and modifications. There is a lot more documentation in the docs of the mongo shell equivalent. Example:

    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() will perform a set of bulk write operations. The BulkWrite API was only introduced a couple of days ago for the go driver. There are little examples, however you can always check the tests files. Example:

    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,
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计