Write a MongoDB aggregation query to group and calculate the average of a field in a collection.
Write a MongoDB aggregation query to group and calculate the average of a field in a collection.
19626-Jul-2023
Home / DeveloperSection / Forums / Write a MongoDB aggregation query to group and calculate the average of a field in a collection.
Write a MongoDB aggregation query to group and calculate the average of a field in a collection.
Aryan Kumar
27-Jul-2023Sure, here is a MongoDB aggregation to group and calculate the average of a field in a collection:
This aggregation will group the documents in the collection by the value of the
field
field. For each group, the average of thefield
field will be calculated and stored in theaverage
field.For example, if the collection contains the following documents:
The aggregation will produce the following output:
The
_id
field in the output documents is the value of thefield
field in the original documents. Theaverage
field is the average of thefield
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 themongo
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.