Question

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.

Was it helpful?

Solution

The following works for me from the mongo shell - so I'm not sure what happened above for you. Try this and see if it works? If so I would say grab the latest mongo code in case something used to be problematic.

x = { 'name': 'test', anotherdoc: { 'something': 'someval', somenum : 1 } }
> x
{"name" : "test" , "anotherdoc" : {"something" : "someval" , "somenum" : 1}}
> collection = db.foo;
test.foo
> collection.insert(x)
> collection.find()
{"_id" :  ObjectId( "4a61b6711591f41f0f1bc5ff")  , "name" : "test" , "anotherdoc" : {"something" : "someval" , "somenum" : 1}}
> x
{"name" : "test" , "anotherdoc" : {"something" : "someval" , "somenum" : 1}}
> x._id
> x = collection.findOne()
{"_id" :  ObjectId( "4a61b6711591f41f0f1bc5ff")  , "name" : "test" , "anotherdoc" : {"something" : "someval" , "somenum" : 1}}
> collection.update({'_id': x._id}, {$set: {'anotherdoc.something': 'somenewval'}} )
> collection.find()
{"_id" :  ObjectId( "4a61b6711591f41f0f1bc5ff")  , "name" : "test" , "anotherdoc" : {"somenum" : 1 , "something" : "somenewval"}}
> 

As mentioned above, the MongoDB forums probably get seen faster (or try IRC).

OTHER TIPS

You'd better ask this in mongodb user's googlegroup. The answer for your question is here http://groups.google.com/group/mongodb-user/msg/583d37ef41ef5cca?hl=en

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top