How to retrieve a specific field from a subdocument array with mongoose How to retrieve a specific field from a subdocument array with mongoose mongodb mongodb

How to retrieve a specific field from a subdocument array with mongoose


The projection available to .find() queries generally in MongoDB does not do this sort of projection for internal elements of an array. All you can generally do is return the "matched" element of the array entirely.

For what you want, you use the aggregation framework instead, which gives you more control over matching and projection:

Model.aggregate([    { "$match": {        "hierarchies.userId": ObjectId("53a47a639c52c9d83a2d71db")    }},    { "$unwind": "$hierarchies" },    { "$match": {        "hierarchies.userId": ObjectId("53a47a639c52c9d83a2d71db")    }},    { "$project": {        "rank": "$hierarchies.rank"    }}],function(err,result) {})

That basically matches the documents, filters the array content of the document to just the match and then projects only the required field.