Home > Enterprise >  How to add conditionally an element in an array in mongodb?
How to add conditionally an element in an array in mongodb?

Time:11-27

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

  • Related