首页 > 解决方案 > 批量写入时输入了错误的数据

问题描述

我正在使用 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[]mongo.WriteModelin for 循环的类型,我将单个文档附加到操作中,但另一方面,当我在 mongodb 中验证所有文档都在那里时,只有最后一个文档在 mongodb 中写入了 1000 次。请让我知道上面代码段中的哪一行代码是错误的。

提前致谢!

标签: mongodbgo

解决方案


您正在引用相同的变量并再次更新它,因此在迭代之后,您只有最后一条记录 * 循环运行的次数。

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)
}

推荐阅读