---
title: "Write a MongoDB aggregation query to group and calculate the average of a field in a collection."  
description: "Write a MongoDB aggregation query to group and calculate the average of a field in a collection."  
author: "Steilla Mitchel"  
published: 2023-07-26  
updated: 2023-07-27  
canonical: https://www.mindstick.com/forum/159301/write-a-mongodb-aggregation-query-to-group-and-calculate-the-average-of-a-field-in-a-collection  
category: "mongodb"  
tags: ["database", "mongodb"]  
reading_time: 2 minutes  

---

# Write a MongoDB aggregation query to group and calculate the average of a field in a collection.

Write a [MongoDB aggregation](https://www.mindstick.com/forum/158369/what-is-the-purpose-of-the-mongodb-aggregation-framework-and-how-to-use-it) [query](https://www.mindstick.com/blog/202/sub-query-in-sqlserver) to [group](https://yourviews.mindstick.com/view/81323/adani-green-energy-group-bags-world-s-biggest-solar-bid) and calculate the average of a [field](https://www.mindstick.com/forum/160867/does-mindstick-provide-training-for-field-marketing) in a collection.

## Replies

### Reply by Aryan Kumar

Sure, here is a [MongoDB](https://www.mindstick.com/articles/337565/understanding-document-stores-a-look-at-mongodb-vs-couchdb) [aggregation](https://www.mindstick.com/forum/217/what-is-aggregation-and-how-it-maps-into-a-java-class) to group and calculate the average of a field in a collection:

```plaintext
db.collection.aggregate([
  {
    $group: {
      _id: "$field",
      average: {
        $avg: "$field"
      }
    }
  }
]);
```

This aggregation will group the documents in the collection by the value of the `field` field. For each group, the average of the `field` field will be calculated and stored in the `average` field.

For example, if the collection contains the following documents:

```plaintext
{ "field": 10 }
{ "field": 20 }
{ "field": 30 }
```

The aggregation will produce the following output:

```plaintext
{ "_id": 10, "average": 15 }
{ "_id": 20, "average": 20 }
{ "_id": 30, "average": 30 }
```

The `_id` field in the output documents is the value of the `field` field in the original documents. The `average` field is the average of the `field` field in the documents that were grouped together.

To run this aggregation, you can use the `mongo` shell or a MongoDB driver. For example, to run the aggregation using the `mongo` shell, you would use the following command:

mongo <database> <collection> --eval "db.collection.aggregate([{ $group: { _id: '$field', average: { $avg: '$field' } } }])"

Replace `<database>` and `<collection>` with the name of the database and collection that you want to use.


---

Original Source: https://www.mindstick.com/forum/159301/write-a-mongodb-aggregation-query-to-group-and-calculate-the-average-of-a-field-in-a-collection

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
