Tuesday 6 June 2017

MongoDB - Update query: Find and push into an array within another array of objects [duplicate]

This question already has an answer here:

Hey guys am not great at Mongo querying, yesterday I got suck here - the case is below:

So here's the SCHEMA that I have

 schema:{
     name: String,
     members:[{
        user_id: String,
        status: String,
        branches: [] 
     }]
   }

When there is DATA inside, its like:

[{
   _id: 122,
   name: "Waka Waka",
   arr:[
      {
         _id: 123,
         user_id: "12u456830mj4",
         status: "poisoned",
         arr_arr: []
      },{
         _id: 321,
         user_id: "12u456830mj4",
         status: "healed",
         arr_arr: [] //  <== THIS is where I want to push data ("rice")
      }
   ]
}]

What I WANT:

A find and update query

  • Which will find the collection for arr element with _id: 321, ie find(arr._id: 321) and
  • PUSH value rice inside index arr_arr of the found $ document.

What I have tried:

Collection.update(
    {_id: 123, "arr._id": 321}, 
    {
        $push: { $set: { "arr.$.arr_arr": "rice"} }
    },
    function(err, updt){
      if(err) {};
      else {}
    }
)

And another with $set first and $push inside. But they are not working .

Please help me out with a mongo query. Thanks.



via Siddhartha Chowdhury

No comments:

Post a Comment