MongoDB更新嵌套数组

时间:2016-09-06 01:42:10

标签: arrays node.js mongodb

我有以下JSON:

{
"_id" : ObjectId("57ce1a55899bf934e59edd0d"),
"project_name" : "Coupletones",
"list_users" : [
    "testmail"
],
"iterations" : [
    {
        "iteration_name" : "Iteration1",
        "tasks" : [ ]
    },
    {
        "iteration_name" : "Iteration2",
        "tasks" : [ ]
    },
]
}

我希望能够将事物推送到与迭代2相关联的任务数组中。如何正确查询并插入到正确的位置?这是我到目前为止所做的,但它总是插入与迭代1相关的任务数组。

var ans = collection_projects.update({
      "project_name" : project_name,
      "list_users" : email,
      "iterations.iteration_name": iteration_name,
      },

      {$addToSet: {"iterations.$.tasks": {
        task_name: task_name,
        task_description : task_description,
        task_assignee: task_assignee,
        task_status : -1 } } }
    );

我见过这个: MongoDB nested array query 但他只是试图推动一个嵌套阵列。

1 个答案:

答案 0 :(得分:1)

尝试这种方法

conditions = {
    "_id": ObjectId"57ce1a55899bf934e59edd0d",
    "iterations.iterations_name": "Iteration2"
  };
updates = {
   $push: {
     "iterations.$.tasks": "success"
   }
};
options = {
  upsert: true
};
Model.update(conditions, updates, options, callback);