亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

大容量寫入時輸入的數據錯誤

大容量寫入時輸入的數據錯誤

Go
米脂 2022-08-15 19:43:19
我正在使用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)

}


查看完整回答
反對 回復 2022-08-15
  • 1 回答
  • 0 關注
  • 158 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號