高朗。MongoDB bulkWrite() 更新文档切片

Yur*_*ura 7 go mongodb

我有一部分对象要保存到 Mongo 集合中。让我们说

type (
    User struct {
        AccountId       string
        Name            string
        FamilyName      string
        EmailAddress    string
    }
)

func persistUsers(ctx context.Context, db *mongo.Collection, users []User) {

}
Run Code Online (Sandbox Code Playgroud)

有些用户已经被保存,有些则没有。我想向上插入切片。因此我有两个问题:

  1. 我怎样才能使用mongo.Collection.BulkWrite()?我找不到如何将对象切片放入其中的明显解释。

  2. mongo 如何决定什么是新的,什么是旧的,必须更新?根据_id?

Wan*_*iar 11

如何使用 mongo.Collection.BulkWrite()?

此示例代码基于MongoDB Go 驱动程序v1.1.2。首先,您需要导入以下内容:

"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/bson"
Run Code Online (Sandbox Code Playgroud)

下面是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:"john@example.org"}

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":"jane@example.org"})
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)
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅:

mongo 如何决定什么是新的,什么是旧的,必须更新?

如果没有与查询条件(过滤器)匹配的文档,则update()插入单个文档。如果存在与查询条件匹配的文档,则它成为更新。有关更多信息,另请参阅Upsert 行为

如果您更新的查询条件中包含_id点符号,请参阅下面的Upsert用点_id查询

  • @WanBachtiar 去``operationB.SetUpdate(bson.M{"$set": data})``` (2认同)