如何在 Go 编程语言中利用 MongoDB 的驱动程序执行批量更新操作
时间:2024-03-03
浏览: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学习网公众号,带你了解更多关于的知识点!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
