Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

148
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda