Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

146
Views
Wrong data entered on bulk write

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!

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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)
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!