How can i find object from an array in mongoose

13,069

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"
    }
  ]
}
Share:
13,069
Kundu
Author by

Kundu

Updated on June 27, 2022

Comments

  • Kundu
    Kundu almost 2 years

    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.

  • Kundu
    Kundu over 10 years
    Thanks for your reply. Your answer give me the whole array. But I want only the particular object of the array. If you have any suggestion reply me.