3

I have the following document

{
  "_id": "A",
  "partsIds": [
    {
      "partId": "B",
      "someOtherField": "value"
    },
    {
      "partId": "C",
      "someOtherField": "value"
    }
  ]
}

Now, what I am trying to achieve is $addToSet to the partsIds array, using the partId field value.

So, what I do is

collection.update({ _id: 'A' }, { $addToSet: { partsIds: { partId: 'B' } } }, {upsert: true});

This operation adds a new object to partsIds array no matter what.

What I am trying to achieve from this is find if partId === 'B' exists don't add anything, if it doesn't, it adds it to partsIds array.

How can I achieve this using mongodb?

I found this answer Using Mongoose / MongoDB $addToSet functionality on array of objects

But it doesn't solve my problem, since it adds a new document when used with upsert.

The way I approached this to get the desired behavior is the following, but I am wondering if there is a way to fully do this on mongo side in one go.

let doc = collection.findOne({ _id: 'A', 'partsIds.partId': 'B' });
if (!doc) {
  collection.update({ _id: 'A' }, { $push: { partsIds: { partId: 'B' } } }, { upsert: true });
}
3
  • Thats the expected behavior. Your addtoset document should match the nested document you are trying to update. Commented Mar 16, 2018 at 22:26
  • Well, it doesn't work that way. I had to do this to get the desired behavior: let doc = collection.findOne({_id:"A", 'partsIds.partId':'B'}); if(!doc) { collection.update({ _id: 'A' }, { $push: { partsIds: { partId: 'B' } } }, {upsert: true}); } Commented Mar 16, 2018 at 22:29
  • Have you found a way since? I'm tryin to do the same kind of update using mongoose and struggling finding how without 2 calls as you do Commented Jun 18, 2021 at 15:44

0

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.