MongoDB query to get average in aggregation of array element?

MongoDBDatabaseBig Data Analytics

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 }
raja
Published on 15-May-2020 06:29:31
Advertisements