Projection and group on nested object mongodb aggregation query

Viewed 19

How to get the nested object in projection and group in mongodb aggregate query.

[
  {
      city: "Mumbai",
      meta: {
        luggage: 2,
        scanLuggage: 1,
        upiLuggage: 1
      },
      cash: 10
},
{
  city: "Mumbai",
  meta: {
    luggage: 4,
    scanLuggage: 3,
    upiLuggage: 1
  },
  cash: 24
},
]

I want to $match the above on the basis of city, and return the sum of each luggage type. My code is as follows but $project is not working -


City.aggregate([
  {
    $match: { city: 'Mumbai' }
  },
  {
    $project: {
      city: 1,
      mata.luggage: 1,
      meta.scanLuggage: 1,
      meta.upiLuggage: 1
    }
  },
  {
    $group: {
      id: city,
      luggage: {$sum: '$meta.luggage'},
      scanLuggage: {$sum: '$meta.scanLuggage'},
      upiLuggage: {$sum: '$meta.upiLuggage'}
    }
  }
])

But the $project is throwing error. I want my output to look like -

{
  city: 'Mumbai',
  luggage: 6,
  scanLuggage: 4,
  upiLuggage: 2
}
1 Answers

You should specify nested fields in quotes when using in $project, and also for grouping key should be _id.

db.collection.aggregate([
  {
    $match: {
      city: "Mumbai"
    }
  },
  {
    $project: {
      city: 1,
      "meta.luggage": 1,
      "meta.scanLuggage": 1,
      "meta.upiLuggage": 1
    }
  },
  {
    $group: {
      _id: "$city",
      luggage: {
        $sum: "$meta.luggage"
      },
      scanLuggage: {
        $sum: "$meta.scanLuggage"
      },
      upiLuggage: {
        $sum: "$meta.upiLuggage"
      }
    }
  }
])

This is the playground link.

Related