MongoDB query to get average in aggregation of array element?


To get an average of array elements, use $avg. Let us create a collection with documents −

> db.demo584.insertOne({"Marks":[75,50,85,60,80]});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e91d827fd2d90c177b5bcc2")
}

Display all documents from a collection with the help of find() method −

> db.demo584.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e91d827fd2d90c177b5bcc2"),
   "Marks" : [
      75,
      50,
      85,
      60,
      80
   ]
}

Following is the query to find avg in the aggregation of array element −

> db.demo584.aggregate([
...    { $project: { MarksAvg: { $avg: "$Marks"} } }
... ])

This will produce the following output −

{ "_id" : ObjectId("5e91d827fd2d90c177b5bcc2"), "MarksAvg" : 70 }

Updated on: 15-May-2020

758 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements