cripebo
cripebo

Reputation: 3

Get all elements in nested array that matches a condition in MongoDB

I'm making a web app using MEAN stack and i'm having some problems making queries with Mongo. I want to get nested object that match a condition. I have a collection of races that looks like the following:

[
  {
        "_id": 412414,
        "name": "Race Name",
        "distance": 16093.4,
        "country": "United Kingdom",
        "city": "Canterbury",
        "date": "2019-01-27",
        "results": [
               {
                  "rank": 1,
                  "name": "Charles Winner",
                  "gender": "M",
                  "age": 34
               },
               {
                  "rank": 2,
                  "name": "Sarah Second",
                  "gender": "F",
                  "age": 29
               },
               {
                  "rank": 3,
                  "name": "John Notwinner",
                  "gender": "M",
                  "age": 34
               },
               {...}
        ]
  },
  {
        "_id": 5554454,
        "name": "Race Name",
        "distance": 16093.4,
        (... more like this)
  }
]

So I want to get all results that matches gender equals to "F" and _id equals to 412414 like:

[
 {
                  "rank": 2,
                  "name": "Sarah Second",
                  "gender": "F",
                  "age": 
 },
 {...more results that match gender : "F"}
]

How can I get it?

Upvotes: 0

Views: 653

Answers (1)

Himanshu Sharma
Himanshu Sharma

Reputation: 3010

The following query can get you the expected output:

db.collection.aggregate([
    {
        $match:{
            "_id": 412414
        }
    },
    {
        $addFields:{
            "results":{
                $filter:{
                    "input":"$results",
                    "as":"result",
                    "cond":{
                        $eq:["$$result.gender", "F"]
                    }
                }
            }
        }
    }
]).pretty()

We are using the $filter aggregator to filter those entries which have gender as 'F'.

Upvotes: 1

Related Questions