2

Is it possible to update a single document field in the Level3 array using $update and $elemMatch? I realize I cannot use the positional operator multiple times given this case and historically I've modified the Level2 nested document with the required deeper changes since these documents aren't very large. I'm hoping there is some syntax that makes it possible to update Level3 array documents using $elemMatch without knowing the position of the target document in the Level3 array or containing document in Level2.

Example:

db.collection.update({_id:'123', level2:{$elemMatch:{'level3.id':'bbb','level3.e1':'hij'}},{'level2.level3.createdDate':new Date()})

{
    _id:'123',
    f1:'abc',
    f2:'def',
    level2:[
        {_
            id:'aaa',
            e1:'hij',
            e2:'lmo'
            level3:[
                {
                    name:'foo',
                    type:'bar',
                    createdDate:'2013-3-28T05:18:00'
                }]
        },
        {_
            id:'bbb',
            e1:'hij',
            e2:'lmo'
            level3:[
                {
                    name:'foo2',
                    type:'bar2',
                    createdDate:'2013-3-28T05:19:00'
                }]
        }
    ]
}
1
  • +1, could use some help on this too Mar 29, 2013 at 0:53

1 Answer 1

1

There is no way to do this currently using a regular update operation for reasons you noted.

The only work around you can use at the moment is to add versioning to your document and use optimistic locking by reading the document, finding the appropriate elements to modify in your application, changing their values and then using an update that includes the version in the read document (so that if other thread updated the document between your query and your update you would not overwrite the changes but would have to reload the document and try again.

The versioning strategy would not have to be based on the entire document, you can version the first level array elements and then you would be able to update just the sub-array you were concerned with (via an update with $set).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.