mongodb - 批量写入时输入了错误的数据
问题描述
我正在使用 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.WriteModel
in for 循环的类型,我将单个文档附加到操作中,但另一方面,当我在 mongodb 中验证所有文档都在那里时,只有最后一个文档在 mongodb 中写入了 1000 次。请让我知道上面代码段中的哪一行代码是错误的。
提前致谢!
解决方案
您正在引用相同的变量并再次更新它,因此在迭代之后,您只有最后一条记录 * 循环运行的次数。
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)
}
推荐阅读
- c++ - 按值返回与右值引用
- tensorflow - 如何将重新训练的模型转换为 tflite 格式?
- php - 使用 PHP 解析具有多级的 json 对象的一部分
- socialengine - Engine_Api::_()->getTable 返回的内容
- c# - 如何将游戏对象向操纵杆旋转
- c# - 如何从 Entity Framework Core 中的内部连接中的多行创建列表?
- c# - 向 COM 接口添加方法后出现 COM 异常 [过程编号超出范围]
- python - Anaconda Python 对隔离环境的支持
- ruby-on-rails - 创建对象时传递参数没有控制器问题的模型
- spring-boot - 我正在使用 Spring Jpa Repository 来执行所有数据库操作。我不知道如何在不使用任何查询的情况下从表中选择特定值