Aggregation framework to get the name of students with test one score less than the total average of all the tests


For this, you can use aggregate(). We have considered test records as “Value1”, “Value2”, etc. Let us create a collection with documents −

> db.demo432.insertOne(
...    {
...       "_id" : 101,
...       "Name" : "David",
...       "Value1" : 67,
...       "Value2" : 87,
...       "Value3" : 78
...    }
... )
{ "acknowledged" : true, "insertedId" : 101 }
> db.demo432.insertOne(
...    {
...       "_id" : 102,
...       "Name" : "Sam",
...       "Value1" : 98,
...       "Value2" : 45,
...       "Value3" : 90
...    }
... )
{ "acknowledged" : true, "insertedId" : 102 }

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

> db.demo432.find();

This will produce the following output −

{ "_id" : 101, "Name" : "David", "Value1" : 67, "Value2" : 87, "Value3" : 78 }
{ "_id" : 102, "Name" : "Sam", "Value1" : 98, "Value2" : 45, "Value3" : 90 }

Following is the query to get the name of students with test one score to be less than average of all the tests −

> db.demo432.aggregate([{
...    $project: {
...       Name: '$Name',
...       Value1: '$Value1',
...       average: {
...          $avg: ['$Value1', '$Value2', '$Value3']
...          }
...       }
...    },
...    {
...    $group: {
...       _id: null,
...       NameValue1: {
...          $push: {
...             "Name": "$Name",
...             "Value1": "$Value1"
...          }
...       },
...       totalAverage: {
...          $avg: '$average'
...          }
...       }
...    },
...    { $project:
...    { lessthanAverageNames:
...    {
...       $map:
...       {
...          input: {
...             $filter: {
...                input: "$NameValue1",
...                as: "out",
...                cond: {
...                   $lt: ["$$out.Value1", "$totalAverage"]
...                   }
...                }
...             },
...             as: "o",
...             in: "$$o.Name"
...             }
...          }
...       }
...    }
... ]);

This will produce the following output −

{ "_id" : null, "lessthanAverageNames" : [ "David" ] }

Updated on: 03-Apr-2020

73 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements