Hi all!
Lately I’m using the aggregations functionality to update a document using the update command. I’m using MongoDB 4.2 version.
My doc look like this:
{
"_id" : 2,
"items" : [
{
"id": 1,
"name": "test",
"value": 5
},
{
"id": 2,
"name": "test2",
"value": 10
},
{
"id": 3,
"name": "test3",
"value": 15
}
],
};
I want to update a specific value in the array items filtering by id, but I have the next requirement: different users can update this items and it can changes the position of them in any time, so after an user’s change the items can look like this:
{
"_id" : 2,
"items" : [
{
"id": 2,
"name": "test2",
"value": 10
},
{
"id": 1,
"name": "test",
"value": 5
},
{
"id": 3,
"name": "test3",
"value": 15
}
],
};
So, if two users launch a concurrent update about the same item, like item with id 2, one of them to update value and the other to change the position in the array, both operations must be success.
Reviewing the documentation, I can get this behavior using the array expression operator, but the problem is I cannot update a single item in this array (or I have not found the way to do it), I must use the $map (or $reduce) operator to loop though the array, update the single item, and set the whole array to the field “items”.
So the question is: there is any way to update only a single item in the array using aggregation expressions???
Update the item using an expression like this:
{"items.0": <expression for update item with id equal to 0>}
will not work because other user can change the position in the array previously, so it’s not guaranteed the item with id equal to 0 is going to be in position 0.