How can I get the projection of some fields of a specific document embedded in an array?

Viewed 30

Consider the following (simplified) example:

{
  _id: 1,
  name: "Andrew",
  role: "ATT",
  Sesons: [
            {
             year: "2018-2019",
             age: 20,
             goals: 10
             }, 
             {
             year: "2019-2020",
             age: 21,
             goals: 101
             }]
}
{
  _id: 2,
  name: "Paul",
  role: "DF",
  Sesons: [
            {
             year: "2018-2019",
             age: 15,
             goals: 102
             }, 
             {
             year: "2019-2020",
             age: 16,
             goals: 1
             }]
}

How can I get this specific result from a query, based on {"Seasons.year": "2019-2020"} for example ?

{_id: 2, name: "Paul", role: "DF", Seasons: {age: 16}}

And how can I get this result from a query by getting an entire embedded document?

{_id: 2, name: "Paul", role: "DF", Seasons: {year: "2018-2019", age: 16, goals: 1}}

Thank you so much! I apologize for the question, perhaps, not correctly formatted, but it is my first question about Stack Overflow.

1 Answers

You can use projection.You can query like following.

[
  {
    $match: {
      "_id": 2
    }
  },
  {
    $project: {
      _id: 1,
      name: 1,
      role: 1,
      Sesons: {
        $filter: {
          input: "$Sesons",
          cond: {
            $eq: [
              "$$this.year",
              "2019-2020"
            ]
          }
        }
      }
    }
  }
]

Working Mongo playground . Once you get your result, again use the $project to get only age with other fields. Eg :

{
    $project: {
      "Sesons.year": 0,
      "Sesons.goals": 0
    }
  }
Related