I need to add an element to an array in mongoDB, but only id it doesn't already exist. For now I do as follows:
await db
.collection(config.MY_COLLECTION)
.updateOne(
{ _id: ObjectId(userId) },
{ $push: { my_array: ObjectId(idToAdd) } }
);
In this way I can add the same element x times. How can I avoid it without querying the DB before and do it conditionally server side. I want to do it directly DB side.
CodePudding user response:
Just replace $push with $addToSet