The mongodb collection looks like the array below
[
{
"_id": 1,
"arr": [
{
"key": "abc",
"val_a": 2
}
]
},
{
"_id": 2
}
]
What I want to do is increment 1 to the element in arr array with key def. If the element with key def is not in the array arr, I want to add a new element like below to arr
{
"key": "def",
"val_a": 1
}
I tried
db.collection.update({
"_id": 1,
"arr.key": "def",
},
{
"$inc": {
"arr.$.val_a": 1
}
})
But it is not adding the new element. The result is like
[
{
"_id": 1,
"arr": [
{
"key": "abc",
"val_a": 2
}
]
},
{
"_id": 2
}
]
What I am expecting is something like this:
[
{
"_id": 1,
"arr": [
{
"key": "abc",
"val_a": 2
},
{
"key": "def",
"val_a": 1
}
]
},
{
"_id": 2
}
]
I want to do it in one operation as I am intending to do is a BulkWrite operation with UpdateOneModel.