Tutorialspoint

1 Answer
Smita Kapse

Use $avg operator along with aggregate framework. Let us first create a collection with documents. Here, one of the fields is StudentScore −

> db.averageReturiningNullDemo.insertOne(
   {"StudentDetails" : { "StudentScore" : 89 }
});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce9822e78f00858fb12e927")
}
> db.averageReturiningNullDemo.insertOne(
   {"StudentDetails" : { "StudentScore" : 34 }
});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce9822e78f00858fb12e928")
}
> db.averageReturiningNullDemo.insertOne(
   {"StudentDetails" : { "StudentScore" : 78 }
});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce9822e78f00858fb12e929")
}

Following is the query to display all documents from a collection with the help of find() method −

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

This will produce the following output −

{
   "_id" : ObjectId("5ce9822e78f00858fb12e927"),
   "StudentDetails" : {
      "StudentScore" : 89
   }
}
{
   "_id" : ObjectId("5ce9822e78f00858fb12e928"),
   "StudentDetails" : {
      "StudentScore" : 34
   }
}
{
   "_id" : ObjectId("5ce9822e78f00858fb12e929"),
   "StudentDetails" : {
      "StudentScore" : 78
   }
}

Following is the query to average returning −

> db.averageReturiningNullDemo.aggregate([
   {
      "$group": {
         "_id": null,
         "StudentScoreAverage": {
            "$avg": "$StudentDetails.StudentScore"
         }
      }
   }
]);

This will produce the following output −

{ "_id" : null, "StudentScoreAverage" : 67 }

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.