使用MongoDB的bulkWrite()批量更新文档片段
来源:stackoverflow
时间:2024-03-04 16:09:26 137浏览 收藏
哈喽!今天心血来潮给大家带来了《使用MongoDB的bulkWrite()批量更新文档片段》,想必大家应该对Golang都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到,若是你正在学习Golang,千万别错过这篇文章~希望能帮助到你!
我有一个对象切片想要保存到 mongo 集合中。这么说吧
type (
User struct {
AccountId string
Name string
FamilyName string
EmailAddress string
}
)
func persistUsers(ctx context.Context, db *mongo.Collection, users []User) {
}
有些用户已经保存,有些则没有。我想更新插入切片。因此我有两个问题:
如何使用
mongo.collection.bulkwrite()?我找不到明显的解释如何将对象切片放入其中。mongo 如何决定什么是新的、什么是旧的以及必须更新的?根据
_id?
解决方案
如何使用 mongo.collection.bulkwrite()?
此示例代码基于 MongoDB Go driver v1.1.2。首先您需要导入以下内容:
"go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/bson"
下面是 Collection.BulkWrite 的示例代码,并使用您的 user 结构示例:
collection := client.database("databasename").collection("collectionname")
var operations []mongo.writemodel
// example using user struct
usera := user{accountid:"1", name:"john", familyname:"smith", emailaddress:"<a target='_blank' href='https://www.17golang.com/gourl/?redirect=MDAwMDAwMDAwML57hpSHp6VpkrqbYLx2eayza4KafaOkbLS3zqSBrJvPsa5_0Ia6sWuR4Juaq6t9nq6ycZqKgG2svpXKqIBkrtu-i2LMmbrbrZuueqbGeYaeyYCkppKihqKu3LOijnmMlbN4cpSSt89pkqp5qLBkep6yo6Nkf42hpLLdyqKBrIXRsot-lpHdz3Y' rel='nofollow'>[email protected]</a>"}
operationa := mongo.newupdateonemodel()
operationa.setfilter(bson.m{"accountid": usera.accountid})
operationa.setupdate(bson.m{"name":usera.name,
"familyname":usera.familyname,
"emailaddress":usera.emailaddress})
// set upsert flag option to turn the update operation to upsert
operationa.setupsert(true)
operations = append(operations, operationa)
// example using bson.m{}
operationb := mongo.newupdateonemodel()
operationb.setfilter(bson.m{"accountid":2})
operationb.setupdate(bson.m{"name":"jane",
"familyname":"smith",
"emailaddress":"<a target='_blank' href='https://www.17golang.com/gourl/?redirect=MDAwMDAwMDAwML57hpSHp6VpkrqbYLx2eayza4KafaOkbLS3zqSBrJvPsa5_0Ia6sWuR4Juaq6t9nq6ycZqKgG2svpXKqIBkrtu-i2LMmbrbrZuueqbGeYaeyYCkppKihqKu3LOijnmMlbN4cpSSt89pkqp5qLBkep6yo6Nkf42hpLLdyqKBrIXRsot-lpHdz3Y' rel='nofollow'>[email protected]</a>"})
operationb.setupsert(true)
operations = append(operations, operationb)
// specify an option to turn the bulk insertion in order of operation
bulkoption := options.bulkwriteoptions{}
bulkoption.setordered(true)
result, err := collection.bulkwrite(context.todo(), operations, &bulkoption)
if err != nil {
log.fatal(err)
}
fmt.println(result)
更多信息请参见:
- mongodb go 驱动程序 options.BulkWriteOptions
- mongodb go 驱动程序 options.UpdateOptions
- mongodb db.collection.bulkWrite()
mongo 如何决定什么是新的、什么是旧的以及必须更新的?
如果没有文档与查询条件(过滤器)匹配,则 update() 会插入单个文档。如果存在符合查询条件的文档,它将成为更新。另请参阅 Upsert Behaviour 了解更多信息。
如果您的更新查询条件包含 _id 和 dot notation,请参阅 Upsert With Dotted _id Query。
任何寻求更新文档集合的特定 key:value 的解决方案的人,
如果该字段不存在,这也会创建一个新文档。
func UpdateData(data []User) {
upsert := true
after := options.After
collection := client.Database("dbname").Collection("colname")
for _, user := range data {
// Create the search filter
filter := bson.M{"name": user.Name}
// Create the update
update := bson.M{
"$set": bson.M{"AccountId": user.AccountID}, // New Account ID
}
// Create an instance of an options and set the desired options.
opt := options.FindOneAndUpdateOptions{
ReturnDocument: &after,
Upsert: &upsert,
}
// Find one result and update it
result := collection.FindOneAndUpdate(context.Background(), filter, update, &opt)
if result.Err() != nil {
log.Printf("user account id update failed: %v\n", result.Err())
}
}
}
参数data []user假设您有一个结构切片,其中包含要在数据库中更新的新值。
文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《使用MongoDB的bulkWrite()批量更新文档片段》文章吧,也可关注golang学习网公众号了解相关技术文章。
-
502 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
139 收藏
-
204 收藏
-
325 收藏
-
478 收藏
-
486 收藏
-
439 收藏
-
357 收藏
-
352 收藏
-
101 收藏
-
440 收藏
-
212 收藏
-
143 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习