node.js MongoDb:如何将附加对象插入对象集合?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17288439/
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
MongoDb : How to insert additional object into object collection?
提问by cpeele00
I have a document "owner" that can have "n" number of camps and camps have "instructors" and instructors have "classes". Earlier I tried accomplishing this with nested arrays (see link to my post below), however I learned that the positional operator "$" does not nest that deep. MongoDB: Adding an array into an existing array
我有一个文件“所有者”,可以有“n”个营地,营地有“讲师”,讲师有“班级”。早些时候,我尝试使用嵌套数组来完成此操作(请参阅下面我的帖子的链接),但是我了解到位置运算符“$”并没有嵌套那么深。 MongoDB:将数组添加到现有数组中
However, I learned that the workaround would be to use object collections instead of arrays. I'm assuming that I have to use "update" with "$set" to add additional "camps", however every time I do all it does is overwrite(update) the previous camp that was inserted.
但是,我了解到解决方法是使用对象集合而不是数组。我假设我必须使用“更新”和“$set”来添加额外的“阵营”,但是每次我做的都是覆盖(更新)插入的前一个阵营。
Below is the hierarchical structure I am trying to accomplish:
下面是我试图完成的层次结构:
owner = {
firstName: 'john',
lastName: 'smith',
ownerEmail: '[email protected]',
camps : {
{
name: 'cubs-killeen',
location: 'killeen'
},
{
name: 'cubs-temple',
location: 'temple'
},
instructors : {
{
firstName: 'joe',
lastName : 'black'
},
{
firstName: 'will',
lastName : 'smith'
}
}
}
}
I have also been trying the following:
我也一直在尝试以下方法:
db.owners.update({ownerEmail:'[email protected]'}, {$set: { camps:{ {name:'cubs-killeen'} } }})
but this throws an unexpected identifier { error.
但这会引发意外的标识符 { 错误。
Any help with some sample mongo commands to achieve the structure above would be most appreciated.
对一些示例 mongo 命令的任何帮助以实现上述结构将不胜感激。
V/R
V/R
Chris
克里斯
回答by AntonioOtero
As other mentioned, The structure you want is not valid. I recommend the following structure for your owner document:
正如其他人提到的,您想要的结构无效。我建议您的所有者文档采用以下结构:
{
"_id" : ObjectId("51c9cf2b206dfb73d666ae07"),
"firstName" : "john",
"lastName" : "smith",
"ownerEmail" : "[email protected]",
"camps" : [
{
"name" : "cubs-killeen",
"location" : "killeen"
},
{
"name" : "cubs-temple",
"location" : "temple"
}
],
"instructors" : [
{
"firstName" : "joe",
"lastName" : "black"
},
{
"firstName" : "will",
"lastName" : "smith"
}
]
}
and then
进而
db.stack.update(
{ ownerEmail: "[email protected]" },
{
$push: {
camps: { name: "cubs-killeen", location: "some other Place" }
}
}
);
Having this, you can add camps like this:
有了这个,你可以添加这样的营地:
Hope it helps.
希望能帮助到你。

