更新 mongodb 中的嵌套文档
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1145956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Updating nested documents in mongodb
提问by defrex
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.
当然,不是我要找的。
采纳答案by defrex
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.
以下从 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"}}
>
As mentioned above, the MongoDB forums probably get seen faster (or try IRC).
如上所述,可能会更快地看到 MongoDB 论坛(或尝试 IRC)。
回答by defrex
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
你最好在 mongodb 用户的 googlegroup 中问这个。您的问题的答案在这里http://groups.google.com/group/mongodb-user/msg/583d37ef41ef5cca?hl=en