Mongoose add multiple object to array if not exist based

You can try using bulkWrite operation in mongodb

Suppose you have following payload to update

const payload = [
  { key: "city", label: "CITY" }, { key: "gender", label: "GENDER" },
  { key: "city", label: "CITY1" }, { key: "city2", label: "CITY" }
]

Query to update documents in bulk

Model.bulkWrite(
  payload.map((data) => 
    ({
      updateOne: {
        filter: { '_id': 'xxxx', 'additional.key' : { $ne: data.key } },
        update: { $push: { additional: data } }
      }
    })
  )
})

Which will send a request in bulk to update like this

bulkWrite([
  { updateOne: { filter: { '_id': 'xxxx', 'additional.key' : { $ne: data.key } }, update: { $push: { additional: data } } } },
  { updateOne: { filter: { '_id': 'xxxx', 'additional.key' : { $ne: data.key } }, update: { $push: { additional: data } } } }
])

Leave a Comment