- 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
How to select documents with values above the average in MongoDB?
Use aggregate() in MongoDB to select documents with values above the average. To find the average, use $avg in MongoDB.
Let us create a collection with documents −
> db.demo552.insertOne({values:10});{ "acknowledged" : true, "insertedId" : ObjectId("5e8e3b1c9e5f92834d7f05ea") } > db.demo552.insertOne({values:50});{ "acknowledged" : true, "insertedId" : ObjectId("5e8e3b1f9e5f92834d7f05eb") } > db.demo552.insertOne({values:40});{ "acknowledged" : true, "insertedId" : ObjectId("5e8e3b289e5f92834d7f05ec") }
Display all documents from a collection with the help of find() method −
> db.demo552.find();
This will produce the following output −
{ "_id" : ObjectId("5e8e3b1c9e5f92834d7f05ea"), "values" : 10 } { "_id" : ObjectId("5e8e3b1f9e5f92834d7f05eb"), "values" : 50 } { "_id" : ObjectId("5e8e3b289e5f92834d7f05ec"), "values" : 40 }
Following is the query to select documents with values above the average −
> var findAvg = db.demo552.aggregate([ ... { "$group": { "_id": "null", Average: { "$avg": "$values"} }} ... ]).toArray()[0]["Average"]; > db.demo552.find({ "values": { "$gt": findAvg } })
This will produce the following output −
{ "_id" : ObjectId("5e8e3b1f9e5f92834d7f05eb"), "values" : 50 } { "_id" : ObjectId("5e8e3b289e5f92834d7f05ec"), "values" : 40 }
Advertisements