我正在使用golang將批量數據寫入monogdb。假設我們有以下數據[ { id:1, name:"abc" } { id:2, name:"cde" } ....upto 1000]為了保存此數據,我正在使用以下代碼對此進行批量寫入操作mongoSession, ctx := config.ConnectDb("myFirstDatabase")defer mongoSession.Disconnect(ctx)var operations []mongo.WriteModeloperationA := mongo.NewInsertOneModel()getCollection := mongoSession.Database("myFirstDatabase").Collection("transactions")for k, v := range transaction { operationA.SetDocument(transaction[k]) operations = append(operations, operationA) fmt.Println(operationA)}bulkOption := options.BulkWriteOptions{}// bulkOption.SetOrdered(true)_, err = getCollection.BulkWrite(ctx, operations, &bulkOption)operations是 for 循環的類型,我將單個文檔附加到操作中,但另一方面,當我在 mongodb 中驗證所有文檔都在那里時,只有最后一個文檔在 mongodb 中寫入了 1000 次。請讓我知道上面的代碼片段中的哪個行代碼是錯誤的。[]mongo.WriteModel
1 回答

慕仙森
TA貢獻1827條經驗 獲得超8個贊
您正在引用同一個變量并再次更新它,因此在迭代后,您只有最后一條記錄 * 循環運行的次數。
operationA.SetDocument(transaction[k])將再次將值n再次設置為同一變量,結果僅使用最后一個值operations = append(operations, operationA)
for k, v := range transaction {
var operationA := mongo.NewInsertOneModel() // create variable with local scope to fix the issue
operationA.SetDocument(transaction[k])
operations = append(operations, operationA)
fmt.Println(operationA)
}
- 1 回答
- 0 關注
- 158 瀏覽
添加回答
舉報
0/150
提交
取消