How can i find object from an array in mongoose How can i find object from an array in mongoose mongoose mongoose

How can i find object from an array in mongoose


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"    }  ]}


You can always get the value of some field by using find(). For example in your case:

db.collectionName.find({},{s.data:1})

So the first bracket is to apply any condition or query, and in the second bracket you have to define the field as 1(to fetch only those fields value).

Please check http://docs.mongodb.org/manual/reference/method/db.collection.find for more information.Let me know if it solves your problem.


Not into Mongo or db but working with Pure JavaSript skills here is the Solution as you mentioned Node.js which would do the execution task of the below.

Schema

   var P = { s : [             {             data : [],             sec : '52b9830cadaa9d273200000d'              },{             data : [],             sec : '52b9830cadaa9d2732000005'              }         ]    };

Search Method Code

var search = function (search_sec){     for (var i=0; i<(P.s.length);i++){       var pointer = P.s[i].sec;       var dataRow = P.s[i];        if((pointer) === search_sec ){             console.log(dataRow);          }      }};

Here is How you can call - search('search_id');

For example input : search('52b9830cadaa9d2732000005');

Output:

 [object Object] {                  data: [],                  sec: "52b9830cadaa9d2732000005"                  }

Working Demo here - http://jsbin.com/UcobuVOf/1/watch?js,console