0

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.

2
  • 1
    Have you checked out $addToSet? Commented Nov 25, 2021 at 21:57
  • Very good @ray! That's the one Commented Nov 25, 2021 at 22:01

1 Answer 1

1

Just replace $push with $addToSet

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.