使用MongoDB的bulkWrite()批量更新文档片段
时间:2024-03-04
浏览: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:"[email protected]"}
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":"[email protected]"})
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学习网公众号了解相关技术文章。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
