Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose select specific fields from array elements

Let's say I have this schema

{
jedi: [{
       name:String
       lightsaber_color:String
      ]}
}

I want to return all and only the names of them. I tried

Jedi.find({})
    .select('jedi.name')
    .exec(function (err, jedi) {
      if (err) {
        console.log("nothing found")
      }
}

It returns me nothing, while this code returns me everything.

Jedi.find({})
        .select('jedi')
        .exec(function (err, jedi) {
          if (err) {
            console.log("nothing found")
          }
    }

I see that jedi is an array so I think that .select('jedi.name') may not work for this reason.
What is the right syntax to do so?

like image 907
r4id4 Avatar asked Jan 07 '16 08:01

r4id4


People also ask

How do I query an array field in MongoDB?

To query if the array field contains at least one element with the specified value, use the filter { <field>: <value> } where <value> is the element value. To specify conditions on the elements in the array field, use query operators in the query filter document: { <array field>: { <operator1>: <value1>, ... } }

How we can return selected columns in mongoose find query?

Mongoose find() Certain Fields To filter object properties in mongoose, you can use the select() function on the query. The select() function allows you to select the fields you wish to return.

How do I match an array in MongoDB?

The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria. If you specify only a single <query> condition in the $elemMatch expression, and are not using the $not or $ne operators inside of $elemMatch , $elemMatch can be omitted.

Can I use $in in mongoose?

For example, if we want every document where the value of the name field is more than one value, then what? For such cases, mongoose provides the $in operator. In this article, we will discuss how to use $in operator. We will use the $in method on the kennel collection.


1 Answers

You can try with this

Jedi.find({}, {'jedi.name':1}, function (err, jedi) {
      if (err) {
        console.log("nothing found")
      }
      else{
        console.log(jedi);
      }
}
like image 112
Soni Pandey Avatar answered Sep 19 '22 16:09

Soni Pandey