MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

crea e aggiorna più documenti MongoDB in una chiamata

Fondamentalmente hai bisogno di bulkWrite operazione con upsert

const array = [
    {  someId: 1, someProp: prop1, isOpen: true  },
    {  someId: 2, someProp: prop1, isOpen: true  },
    {  someId: 5, someProp: prop1, isOpen: true  },
    {  someId: 6, someProp: prop1, isOpen: true  }
]


Model.bulkWrite(
  array.map((data) => 
    ({
      updateOne: {
        filter: { someId: data.someId },
        update: { $set: { isOpen: false, someProp: data.someProp } },
        upsert: true
      }
    })
  )
})

Ti darà l'output

[
  {  someId: 1, someProp: prop1, isOpen: false  },
  {  someId: 2, someProp: prop1, isOpen: false  },
  {  someId: 3, someProp: prop1, isOpen: true  },
  {  someId: 4, someProp: prop1, isOpen: true  },
  {  someId: 5, someProp: prop1, isOpen: true  },
  {  someId: 6, someProp: prop1, isOpen: true  }
]