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 });
}