Alternative for $elemMatch that returns multiple matches

Hi, I’m looking for an alternative for $elemMatch that returns multiple matches

here’s an example:

{
   group:"alpha",
      list:[
         {"name":"Max","age":34},
         {"name":"John","age":39},
         {"name":"Tim","age":42}
      ]
}
Example.find(
   { group : 'alpha' },
   { list : { $elemMatch : { age : { $gte : 39 } } } , group : 1 }
)

Result:

{
   group:"alpha",
      list:[
         {"name":"John","age":39}
      ]
}

what I’m looking for:

{
   group:"alpha",
      list:[
         {"name":"John","age":39},
         {"name":"Tim","age":42}
      ]
}

Thank you.

Hi, @Mahmoud_Mohammad,
Please take a look at this: https://docs.mongodb.com/manual/reference/operator/aggregation/filter/
Thanks,
Rafael,

2 Likes

You can use match after unwind to get all nested elements matching the criteria.
In you example, it would be like
Example.find(
{ group : ‘alpha’ },
{$unwind : list}
{ $match: {list.age : { $gte : 39 } } } }
)

Alternate way to use $filter in projection

Have you tested the above code that you have published. I tried it and I get

MongoError: FieldPath field names may not start with '$'.

Is that possible that you are mistaking find() vs aggregate()?