将新对象插入嵌套数组

时间:2019-04-07 16:00:07

标签: arrays mongodb nested insert-update

我在mongodb中有一个文档,如下所示:

{
   "_id" : 1,
   "name" : "Christine Franklin",
   "degrees" : [
      {
         "level" : "Master",
         info:[ {"major" : "Biology",
         "completion_year" : 2010,
         "faculty" : "Science"}]
      },
    {
         "level" : "Bachelor",
         info : [{"major" : "Biology",
         "completion_year" : 2008,
         "faculty" : "Science"}]
      }
]

}

仅当“级别”为“单身汉”时,我想将new_object(以下提到)添加到数组“信息”中。如何在node.js中编写查询?

new_object = {"major" : "chemistry",
         "completion_year" : 2010,
         "faculty" : "Science"}

最终文档应如下所示:

{
   "_id" : 1,
   "name" : "Christine Franklin",
   "degrees" : [
      {
         "level" : "Master",
         info:[ {"major" : "Biology",
         "completion_year" : 2010,
         "faculty" : "Science"}]
      },
    {
         "level" : "Bachelor",
         info : [{"major" : "Biology",
         "completion_year" : 2008,
         "faculty" : "Science"},{"major" : "chemistry",
         "completion_year" : 2010,
         "faculty" : "Science"}]
      }
]

}

1 个答案:

答案 0 :(得分:0)

您可以在带有arrayFilters选项的update方法中使用$ push运算符

db.test.update(
  { _id: 1 },
  { $push : { "degrees.$[degree].info" : 
      {
          "major" : "chemistry",
          "completion_year" : 2010,
          "faculty" : "Science"
      } 
  }},
{ arrayFilters : [ {"degree.level" : { $eq: "Bachelor" } } ], multi : true }

The filtered positional operator

The $push operator