Given a document as such
{
_id: '123456',
items: [{
itemId: 'abcd',
qty: 1
}, {
itemId: 'defg',
qty: 3
}]
}
I want to only update certain items; for example, I only want to increment itemId = 'abcd'
's quantity by 5
, such that the resulting doc would become
{
_id: '123456',
items: [{
itemId: 'abcd',
qty: 6
}, {
itemId: 'defg',
qty: 3
}]
}
How do I do that?
Basically there are 3 steps :
itemid
from items array where value is abcd$inc
property to increment$
operator (positional update) to specify that you want toIncrement the qty key from the document to be updated.
PFB final query :
db.schools.update({
items.itemId: 'abcd'
},{
$inc : { items.$.qty : 5 }
});