Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating nested documents in mongodb

Tags:

People also ask

How do I update a nested array in MongoDB?

Update Nested Arrays in Conjunction with $[]The $[<identifier>] filtered positional operator, in conjunction with the $[] all positional operator, can be used to update nested arrays. The following updates the values that are greater than or equal to 8 in the nested grades. questions array if the associated grades.


Say I have a data structure something like this:

{
    'name': 'test',
    'anotherdoc': {
        'something': 'someval',
        'somenum': 1
    }
}

Now, say I wanted to set something. Initially, I though it would be done like so:

collection.update({'_id': myid}, {$set: {'anotherdoc.something': 'somenewval'});

This, however, seems to be incorrect. It does put some data in there, but it does so in an odd manner. It would, in this case, end up like so:

[
    {
        'name': 'test',
        'anotherdoc': {
            'something': 'someval',
            'somenum': 1
        }
    },
    ['anotherdoc.something', 'someval']
]

Of course, not what I was looking for.