How to get a specific field from an array of subdocuments using mongoose

I am trying to get a specific field from an array of subdocuments

I will not include any fields in the parent document

Here is a sample document

{ "_id" : ObjectId("5409dd36b71997726532012d"), "hierarchies" : [ { "rank" : 1, "_id" : ObjectId("5409df85b719977265320137"), "name" : "CTO", "userId" : [ ObjectId("53a47a639c52c9d83a2d71db") ] } ] } 

I would like to return the rank of the hierarchy if userId is in the userId array

here is what i still have in my request

 collectionName.find({{hierarchies: {$elemMatch : {userId: ObjectId("53a47a639c52c9d83a2d71db")}}} , "hierarchies.$.rank", function(err,data){} 

still it returns the whole object in the hierarchy array that I want, but I would like to limit it to only the object's rank property.

+5
source share
1 answer

The projection available for .find() queries, as a rule in MongoDB, does not do this kind of projection for the internal elements of an array. All you can usually do is completely return the "consistent" element of the array.

Why do you want to use the aggregation structure , which gives you more control over mapping and projection:

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

This basically matches documents, filters the contents of the document array just for compliance, and then creates only the required field.

0
source

Source: https://habr.com/ru/post/1201930/


All Articles