MongoDb:如何将附加对象插入到对象集合中

MongoDb : How to insert additional object into object collection?

本文关键字:对象 插入 集合 MongoDb      更新时间:2023-09-26

我有一个文档"所有者",可以有"n"个营地,营地有"导师",导师有"课程"。早些时候,我尝试使用嵌套数组来实现这一点(请参阅下面我的文章链接),但我了解到位置运算符"$"的嵌套深度并没有那么深。MongoDB:在现有数组中添加一个数组

但是,我了解到解决方法是使用对象集合而不是数组。我假设我必须使用"更新"answers"$set"来添加额外的"营地",但每次我所做的只是覆盖(更新)之前插入的营地。

以下是我试图实现的层次结构:

owner = {
    firstName: 'john',
    lastName: 'smith',
    ownerEmail: 'john.smith@gmail.com',
    camps : {
        {
            name: 'cubs-killeen',
            location: 'killeen'
        },
        {
            name: 'cubs-temple',
            location: 'temple'
        },
        instructors : {
            {
                firstName: 'joe',
                lastName : 'black'
            },
            {
                firstName: 'will',
                lastName : 'smith'
            }        
        }
    }
}

我也一直在尝试以下内容:

db.owners.update({ownerEmail:'john.smith@gmail.com'}, {$set: { camps:{ {name:'cubs-killeen'} } }})

但是这抛出了一个意外的标识符{error.

如果能通过一些示例mongo命令来实现上述结构,我们将不胜感激。

V/R

Chris

如前所述,您想要的结构无效。我建议您的所有者文档采用以下结构:

    {
    "_id" : ObjectId("51c9cf2b206dfb73d666ae07"),
    "firstName" : "john",
    "lastName" : "smith",
    "ownerEmail" : "john.smith@gmail.com",
    "camps" : [
            {
                    "name" : "cubs-killeen",
                    "location" : "killeen"
            },
            {
                    "name" : "cubs-temple",
                    "location" : "temple"
            }
    ],
    "instructors" : [
            {
                    "firstName" : "joe",
                    "lastName" : "black"
            },
            {
                    "firstName" : "will",
                    "lastName" : "smith"
            }
    ]
}

然后

db.stack.update(
  { ownerEmail: "john.smith@gmail.com" },
  {
    $push: {
      camps: { name: "cubs-killeen", location: "some other Place" }
    }
  }
);

有了这个,你可以添加这样的阵营:

希望能有所帮助。

var newObject = {usuario: req.body.usuario, fecha: req.body.fecha, edit: 
req.body.edit};
await Documentos.findByIdAndUpdate(id,
 { deleted_doc: true,
 $push: { history: newObject } }); 
res.json({ status: 'Documentos Updated' });