Skip to main content

Command Palette

Search for a command to run...

Using MongoDB's Aggregation Framework to Calculate Average Age by City

Published
2 min read

MongoDB's aggregation framework is a powerful tool for processing and analyzing data within your collections. One common use case is to calculate the average age of people grouped by city. This blog will guide you through the process step by step.

Step 1: Setting Up Your Collection

First, ensure you have a MongoDB collection that contains documents with fields for city and age. For example:

{ "name": "Alice", "age": 30, "city": "New York" }
{ "name": "Bob", "age": 25, "city": "Los Angeles" }
{ "name": "Charlie", "age": 35, "city": "New York" }
{ "name": "David", "age": 28, "city": "Los Angeles" }
{ "name": "Eva", "age": 22, "city": "Chicago" }

Step 2: Using the Aggregation Framework

To calculate the average age of people grouped by city, you'll use the $group stage of the aggregation pipeline. The following MongoDB query achieves this:

db.collection.aggregate([
  {
    $group: {
      _id: "$city", // Grouping by city
      averageAge: { $avg: "$age" } // Calculating the average age
    }
  }
])

Step 3: Understanding the Query

  • $group: This operator groups documents by the specified _id field, which in this case is the city.

  • $avg: This operator calculates the average of the specified field, which is age.

Step 4: Running the Query

When you run the above aggregation query, you'll get a result like this:

{ "_id": "New York", "averageAge": 32.5 }
{ "_id": "Los Angeles", "averageAge": 26.5 }
{ "_id": "Chicago", "averageAge": 22 }

Conclusion

Using the aggregation framework in MongoDB makes it easy to perform complex data analysis tasks such as calculating averages. This example demonstrates how you can group documents by a specific field and perform operations on them efficiently.

For more detailed information on MongoDB's aggregation framework, you can visit the MongoDB Aggregation Documentation.

Share Your Thoughts

Have you used the aggregation framework in your projects? What insights did you gain from your data analysis? Share your experiences in the comments!


More from this blog

Amazon S3 Storage Classes

43 posts