I'm writing bulk data into monogdb using golang. Suppose we have below data
[
{
id:1,
name:"abc"
}
{
id:2,
name:"cde"
}
....upto 1000
]
to save this data I'm doing bulk Write operation on this by using below code
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 is type of []mongo.WriteModel in for loop I'm appending the single single doc to operations but on the other hand when I'm verifying in mongodb that all the documents are there then there is only last document that written 1000 times in mongodb. Please let me know which code of line is wrong in the above snippet.
Thanks in advance!
You are referencing the same variable and updating it again, so after iteration, you're having only the last records * the number of times loop ran.
operationA.SetDocument(transaction[k]) will set the value again n again to same variable resulting only last value be used 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)
}