How to add multiple objects to array based on key?
I need to add multiple objects in one query, check if each object key
doesn\'t exist
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 } } } }
])