Problem: I am not able to increment nested array document field as positional operator $ only points to parent array.
Here is my doc firm:
{
"_id" : ObjectId(...),
Whol : [ "name" : 'praveen',
credit_note : [{id : 123, amount : 20 },{id: 456 ,amount : 10},{..}]
]
}
I tried this but doesn't work:
db.firm.update({_id: ,'whol.id':,'whol.credit_note.id' : 123},
{$inc : {'whol.credit_note.$.amount': 100}}
)
Result expected
{
"_id" : ObjectId(...),
Whol : [ "name" : 'praveen',
credit_note : [{id : 123, amount : 120 },{id: 456 ,amount : 10},{..}]
]
}
1 Answer 1
As of my knowledge in mongoDB, you cannot update the document using a single query. Using positional operator ,ドル you can only match a single level of nested array. The object that you have to update is in the second level. Positional operator matching nested array feature is raised in JIRA. You can vote for this feature at https://jira.mongodb.org/browse/SERVER-831
A workaround for this is, you have to find the index of the sub document {id : 123, amount : 20 }. Using this index you can update the document using the query:
db.firm.update({_id: ,'whol.id':,'whol.credit_note.id' : 123},
{$inc : {'whol.$.credit_note.0.amount': 100}})
You will then get the expected result.