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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog