I have a structure that looks like this:
{
_id: 10,
line_items: [
{
_id: 2,
name: "name",
quantity: 2,
},
{
_id: 3,
name: "name2",
quantity: 1,
}
],
sub_total: 100
}
And i'm trying to do an update:
query={_id: 10, 'line_items.$._id': 2}
db.orders.update(query, {$push: {$inc: {'line_items.$.quantity': 1}}, $inc: {sub_total: 32}})
But it doesn't do anything and doesn't show any errors. What's wrong?
CodePudding user response:
There are several issues with your attempt:
- you need to use
$elemMatch
when querying array fields for your case - your $push is incorrect. you can simply use
$inc
Here is a working solution:
db.collection.update({
_id: 10,
line_items: {
$elemMatch: {
_id: 2
}
}
},
{
$inc: {
"line_items.$.quantity": 1,
sub_total: 32
}
})
Here is the Mongo playground for your reference.