在mongodb中更新嵌套文档 [英] Updating nested documents in mongodb
问题描述
说我有一个像这样的数据结构:
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']
]
当然,不是我想要的.
推荐答案
以下内容在mongo shell中对我有效-因此,我不确定上面发生的事情对您有何影响.试试看,看看是否有效?如果是这样,我想说一下,以防万一以前有问题,请获取最新的mongo代码.
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"}}
>
如上所述,MongoDB论坛的访问速度可能更快(或尝试使用IRC).
As mentioned above, the MongoDB forums probably get seen faster (or try IRC).
这篇关于在mongodb中更新嵌套文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!