0

I have the following JSON:

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

I want to be able to push things into to the tasks array associated with Iteration 2. How do I properly query and insert to the correct location? This is what I have so far, but it always inserts into the tasks array associated with Iteration 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 } } }
    );

I've seen this: MongoDB nested array query but he is only trying to push to one nested array.

Community
  • 1
  • 1
srvrdhn
  • 1
  • 1
  • 1
    The [positional update operator](https://docs.mongodb.com/manual/reference/operator/update/positional/) updates the first element it finds in the array, as answered by [Shumi Gupta](http://stackoverflow.com/users/6326976/shumi-gupta) you need to include the element you want to update in de find/condition. One important notice, the positional update updates the first and ONLY the first element. If you need to update multiple elements in an array you (at this moment) need to do it client side. There is a JIRA ticket for this wish – HoefMeistert Sep 06 '16 at 05:14

1 Answers1

2

try by this method

conditions = {
    "_id": ObjectId"57ce1a55899bf934e59edd0d",
    "iterations.iterations_name": "Iteration2"
  };
updates = {
   $push: {
     "iterations.$.tasks": "success"
   }
};
options = {
  upsert: true
};
Model.update(conditions, updates, options, callback);
Shumi Gupta
  • 1,505
  • 2
  • 19
  • 28