Skip to content Skip to sidebar Skip to footer

Select Matching Array Element And Return Selected Fields

I would like to know how to set the projection for a matched array of objects from a Mongoose query. For example, if I have a Mongoose model that looks something like this: var Use

Solution 1:

If you want to only select certain fields of an array to return then you are talking about "reshaping" the document. For anything beyond "basic" field selection, this means using .aggregate() as the method instead of .find().

So the two requirements here are to $filter on the array content to "match" and return, as well as $map the actual "fields to return" from the array itself:

User.aggregate([
  { "$match": { "children.name": "def" } },
  { "$project": {
     "name": 1,
     "children": {
       "$map": {
         "input": {
           "$filter": {
             "input": "$children",
             "as": "c",
             "cond": { "$eq": [ "$$c.name", "def" ] } 
           }
         },
         "as": "c",
         "in": {
           "age": "$$c.age",
           "height": "$$c.height"
         }
       }
     }
  }}
])

Here $filter is used in order to reduce the contents of the array down to only those that match the condition. Being those that have the same "name" property as the value "def". This is then passed as the "input" parameter to $map.

The $map operator works just like it's other language counterparts in that it "reshapes arrays" to return something according to what you specify in the "in" parameter. So here we actually only explicitly name the properties and use there variable assignments for the current array element being processed so that these are what are returned as the "new" array content.

The overall result is an array, containing:

  1. Just the items matching the conditions specified.
  2. Just the fields that were specified to return.

Post a Comment for "Select Matching Array Element And Return Selected Fields"