猿问

大容量写入时输入的数据错误

我正在使用golang将批量数据写入monogdb。假设我们有以下数据


[

 {

   id:1,

   name:"abc"

 }

 {

  id:2,

  name:"cde"

 }

 ....upto 1000

]

为了保存此数据,我正在使用以下代码对此进行批量写入操作


mongoSession, ctx := config.ConnectDb("myFirstDatabase")

defer mongoSession.Disconnect(ctx)

var operations []mongo.WriteModel

operationA := 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


米脂
浏览 193回答 1
1回答

慕仙森

您正在引用同一个变量并再次更新它,因此在迭代后,您只有最后一条记录 * 循环运行的次数。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)}
随时随地看视频慕课网APP

相关分类

Go
我要回答