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 });
}
Hafez
  • 1,320
  • 2
  • 13
  • 24
  • Thats the expected behavior. Your addtoset document should match the nested document you are trying to update. – Krishna Mar 16 '18 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}); }` – Hafez Mar 16 '18 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 – Japsz Jun 18 '21 at 15:44

0 Answers0