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.
Student
I completed my post-graduation in 2013 in the engineering field. Engineering is the application of science and math to solve problems. Engineers figure out how things work and find practical uses for scientific discoveries. Scientists and inventors often get the credit for innovations that advance the human condition, but it is engineers who are instrumental in making those innovations available to the world. I love pet animals such as dogs, cats, etc.
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.