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:
{ "field": 10 }
{ "field": 20 }
{ "field": 30 }
The aggregation will produce the following output:
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:
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Sure, 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
fieldfield. For each group, the average of thefieldfield will be calculated and stored in theaveragefield.For example, if the collection contains the following documents:
The aggregation will produce the following output:
The
_idfield in the output documents is the value of thefieldfield in the original documents. Theaveragefield is the average of thefieldfield in the documents that were grouped together.To run this aggregation, you can use the
mongoshell or a MongoDB driver. For example, to run the aggregation using themongoshell, 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.