Update specific values in a nested array within mongo through mongoose

Update specific values in a nested array within mongo through mongoose

Problem

I have somewhat the following schema(without _id) –

 {uid: String,
 inbox:[{msgid:String, someval:String}]
 }

Now, in the request I get the msgid and I use it in the following mongoose query like this-

 my_model.findOne({'inbox.msgid':'msgidvaluexyz'}
  , function(err, doc) {           
    console.log(doc);
    return !0; })

Now, the problem is that I get the whole document which has the specific message along with the other messages in inbox –

   Output-
   {uid:'xyz',
    inbox:[
     {msgid:,someval},
     {msgid:'our queried msgid',someval}, //required sub array
     {msgid:,someval},
      ]
       }

Now what query can i use to get the specific sub array only as the document inbox is too large to be looped through.

Problem courtesy of: digster

Solution

Use the $ positional selection operator to have the returned doc only include the matched inbox element:

my_model.findOne({'inbox.msgid':'msgidvaluexyz'}
  , {'inbox.$': 1}
  , function(err, doc) {           
    console.log(doc);
    return !0; })
Solution courtesy of: JohnnyHK

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *