0

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

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.

Sign up to request clarification or add additional context in comments.

2 Comments

does 0 index points to searched 123 or its just points to the first element of the array.What if 123 is at 100th position and I don know it index??
0 index will point to the first element of array. You have to get the index programatically and apply it in the second update query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.