登录
首页 >  Golang >  Go问答

如何在 Go 编程语言中利用 MongoDB 的驱动程序执行批量更新操作

来源:stackoverflow

时间:2024-03-03 21:12:28 108浏览 收藏

亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《如何在 Go 编程语言中利用 MongoDB 的驱动程序执行批量更新操作》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下,希望所有认真读完的童鞋们,都有实质性的提高。

问题内容

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

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

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


解决方案


对于您的用例,您将使用 collection.bulkwrite。您可以在存储库的 examples directory 中找到如何使用 go-mongo-driver 的示例。

collection.updatemany() 将使用相同的更新过滤器和修改来更新集合中的多个文档。 mongo shell 等效项的 docs 中有更多文档。示例:

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() 将执行一组 bulk write operations。几天前,对于 go 驱动程序,bulkwrite api 仅是 introduced。例子很少,但是您可以随时检查测试 文件。示例:

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

到这里,我们也就讲完了《如何在 Go 编程语言中利用 MongoDB 的驱动程序执行批量更新操作》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>