6

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.

3 Answers 3

14

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"
    }
  ]
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

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.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.