2016-09-06 156 views
0

我有以下的JSON:MongoDB的更新嵌套数组

{ 
"_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

的[位置更新操作](https://docs.mongodb.com/manual/reference/operator/update/positional/)更新它发现在第一元件数组,如[Shumi Gupta](http://stackoverflow.com/users/6326976/shumi-gupta)回答的那样,您需要在de find/condition中包含要更新的元素。一个重要的通知,位置更新更新第一个和第一个元素。如果您需要更新数组中的多个元素,您(此时)需要在客户端进行更新。有这个愿望的JIRA票 – HoefMeistert

回答

1

尝试通过该方法

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