I have searched SO and crawled the Mongoose / Mongo documentation but to no avail, therefore my question.
I would like to $inc a value in an object that lies within a nested array OR create $setOnInsert this object if it's not there yet.
The Mongo document I have looks as follows:
{
"_id": "123",
"members": [
{
"first": "johnny",
"last": "knoxville",
"score": 2
},
{
"first": "johnny",
"last": "cash",
"score": 3
},
// ...and so on
],
}
Based on this example my use case is to:
- Increment the
countvariable inside the array object if it exists (found based onfirstandlast) - Add an object to the set with
scoreas 1 if it does not exist yet
From this post I understood that I cannot $set a variable that I would like to $inc at the same time. Ok - that makes sense.
This post helped to understand the positional $ operator in order to find the nested object and increment it.
If I know that the document exists, I can simply do the update as follows:
myDoc = { first: 'johnny', last: 'cash' };
myCollection.findOneAndUpdate(
{
_id: '123',
'members.first': 'johnny',
'members.last': 'cash'
},
{
$inc: { "members.$.score": 1 }
}
);
But what if I would like to insert the member (with score: 1) if it doesn't exist yet?
My problem is that when I use upsert: true the positional operator throws an error since it may not be used with upsert (see the official documentation).
I have tried various combinations and would like to avoid 2 db accesses (read / write).
Is there a way to do this in ONE operation?