Sometime in MongoDB, we need to update the object in the array for the particular matching document. We need to update either the first matching object or all the matching objects in the array. Let me give you an example of the documents. Let say I have the following collection whose name is items.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
[
{
"_id" : ObjectId("4faaba123412d654fe83hg876"),
"user_id" : 123456,
"total" : 130,
"items" : [
{
"item_name" : "my_item_one",
"price" : 20
},
{
"item_name" : "my_item_two",
"price" : 50
},
{
"item_name" : "my_item_three",
"price" : 60
}
]
}
]
|
Now I wanted to update the latest price of the item whose name is "my_item_two".
We achieve this through the positional operator ($). The positional operator is used to performing the operation on the particular position. Let me write the query for that:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
db.items.update(
// Match criteria
{
user_id: '123456',
'items.item_name': 'my_item_two'
},
// Update first matching array element using the positional operator ($)
{
$set: {
'items.$.price': 60,
}
}
)
|
This will update the first matching array element but sometime we may need to update all the matching array elements and we can do that by using the $[]. The all positional operator $[]
indicates that the update operator should modify all elements in the specified array field.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
db.items.updateMany(
// Match criteria
{
user_id: '123456',
'items.item_name': 'my_item_two'
},
// Update all matching array element using the positional operator ($)
{
$set: {
'items.$[].price': 60,
}
}
)
|
...