![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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" ] }
Advertisements