Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i find object from an array in mongoose

I have a schema like following : -

var P = {
     s : [{
         data : [],
         sec : mongoose.Schema.Types.ObjectId
     }]
 };

Now I want to find only the object of section not entire the row. Like If I pass sec value I want only the value of s.data of that sec object.

example : -

{ s : [ 
    {
       data : [],
       sec : '52b9830cadaa9d273200000d'
    },{
        data : [],
       sec : '52b9830cadaa9d2732000005'
    }
  ]
}

Result should be look like -

 {
    data : [],
    sec : '52b9830cadaa9d2732000005'
 }

I do not want all entire row. Is it possible? If yes, then please help me.

like image 708
Kundu Avatar asked Dec 26 '13 13:12

Kundu


1 Answers

You can use the $elemMatch projection operator to limit an array field like s to a single, matched element, but you can't remove the s level of your document using find.

db.test.find({}, {_id: 0, s: {$elemMatch: {sec: '52b9830cadaa9d2732000005'}}})

outputs:

{
  "s": [
    {
      "data": [ ],
      "sec": "52b9830cadaa9d2732000005"
    }
  ]
}
like image 93
JohnnyHK Avatar answered Sep 26 '22 15:09

JohnnyHK