How to group nested fields in mongodb aggregation?

Member

by ryleigh , in category: MySQL , a month ago

How to group nested fields in mongodb aggregation?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by hal.littel , a month ago

@ryleigh 

In MongoDB aggregation, you can group nested fields by using the $group stage with the dot notation to access nested fields. Here's an example of how you can group nested fields in MongoDB aggregation:


Suppose you have a collection called "orders" with documents containing nested fields like this:

1
2
3
4
5
6
7
8
{
  "_id": 1,
  "customer": {
    "name": "John Doe",
    "city": "New York"
  },
  "total_amount": 100
}


To group by the "customer.city" field and calculate the total amount for each city, you can use the following aggregation pipeline:

1
2
3
4
5
6
db.orders.aggregate([
  { $group: {
    _id: "$customer.city",
    total: { $sum: "$total_amount" }
  }}
])


In this aggregation pipeline:

  • The $group stage groups the documents by the "customer.city" field using the dot notation.
  • The _id field specifies the field by which to group the documents.
  • The total field uses the $sum operator to calculate the total amount for each city.


After running this aggregation pipeline, you will get the total amount grouped by the "customer.city" field.