【问题标题】:Updating nested documents in mongodb更新 mongodb 中的嵌套文档
【发布时间】:2010-11-11 20:53:03
【问题描述】:

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

{
    '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']
]

当然,不是我想要的。

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    以下内容适用于 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)。

    【讨论】:

    • 嗯,说实话,我是在 python 中做这个测试,而不是在解释器中。如果它与解释器一起工作,问题一定在于我在 python 中的实现。如果我仍然无法正常工作,我会来 MongoDB 论坛。
    • 如果anotherdoc.something 是数组类型,我将如何将另一个元素推送到该类型?
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2016-08-04
      • 1970-01-01
      • 2017-04-28
      • 2014-09-23
      • 1970-01-01
      • 2021-02-13
      • 1970-01-01
      • 2021-11-30
      • 2015-08-27
      相关资源
      最近更新 更多