在mongodb中更新嵌套文档

def*_*rex 15 mongodb

假设我有一个这样的数据结构:

{
    'name': 'test',
    'anotherdoc': {
        'something': 'someval',
        'somenum': 1
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,说我想要设置一些东西.最初,我会这样做:

collection.update({'_id': myid}, {$set: {'anotherdoc.something': 'somenewval'});
Run Code Online (Sandbox Code Playgroud)

然而,这似乎是不正确的.它确实在那里放了一些数据,但它以奇怪的方式实现.在这种情况下,它会像这样结束:

[
    {
        'name': 'test',
        'anotherdoc': {
            'something': 'someval',
            'somenum': 1
        }
    },
    ['anotherdoc.something', 'someval']
]
Run Code Online (Sandbox Code Playgroud)

当然,不是我想要的.

小智 14

下面的例子对我来说是mongo shell - 所以我不确定上面发生了什么.试试这个,看它是否有效?如果是这样,我会说抓住最新的mongo代码以防万一有些问题.

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"}}
> 
Run Code Online (Sandbox Code Playgroud)

如上所述,MongoDB论坛可能会更快(或尝试IRC).