在mongodb中更新嵌套文档

时间:2009-07-17 22:28:15

标签: mongodb

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

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

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

collection.update({'_id': myid}, {$set: {'anotherdoc.something': 'somenewval'});
然而,这似乎是不正确的。它确实在那里放了一些数据,但它以奇怪的方式实现。在这种情况下,它会像这样结束:

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

当然,不是我想要的。

2 个答案:

答案 0 :(得分: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"}}
> 

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

答案 1 :(得分:0)

你最好在mongodb用户的googlegroup中问这个问题。 您的问题的答案在http://groups.google.com/group/mongodb-user/msg/583d37ef41ef5cca?hl=en