- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
MongoDB aggregation to get two documents with the least marks
To get the sorted list of marks, use $sort. Use $limit: 2 to display only two such documents with least marks. Let us create a collection with documents −
> db.demo709.insertOne({Name:"John","Marks":75}); { "acknowledged" : true, "insertedId" : ObjectId("5ea839005d33e20ed1097b76") } > db.demo709.insertOne({Name:"Chris","Marks":45}); { "acknowledged" : true, "insertedId" : ObjectId("5ea839075d33e20ed1097b77") } > db.demo709.insertOne({Name:"David","Marks":54}); { "acknowledged" : true, "insertedId" : ObjectId("5ea839125d33e20ed1097b78") } > db.demo709.insertOne({Name:"Bob","Marks":69}); { "acknowledged" : true, "insertedId" : ObjectId("5ea839295d33e20ed1097b79") }
Display all documents from a collection with the help of find() method −
> db.demo709.find();
This will produce the following output −
{ "_id" : ObjectId("5ea839005d33e20ed1097b76"), "Name" : "John", "Marks" : 75 } { "_id" : ObjectId("5ea839075d33e20ed1097b77"), "Name" : "Chris", "Marks" : 45 } { "_id" : ObjectId("5ea839125d33e20ed1097b78"), "Name" : "David", "Marks" : 54 } { "_id" : ObjectId("5ea839295d33e20ed1097b79"), "Name" : "Bob", "Marks" : 69 }
Following is the query to get two documents with least marks −
> db.demo709.aggregate({ ... $group: { ... _id: '$Marks', ... ListOfName: { $push: '$Name' } ... } ... }, { ... $sort: { ... '_id': 1 ... } ... }, { ... $limit: 2 ... });
This will produce the following output −
{ "_id" : 45, "ListOfName" : [ "Chris" ] } { "_id" : 54, "ListOfName" : [ "David" ] }
- Related Articles
- MongoDB aggregation to fetch documents with specific field value?
- Sort the MongoDB documents in ascending order with aggregation?
- MongoDB Group query to get the count of repeated marks in documents?
- Aggregation in MongoDB for nested documents?
- MongoDB aggregation of elements with similar ids in different documents?
- Get Absolute value with MongoDB aggregation framework?
- Get all the MongoDB documents but not the ones with two given criteria’s?
- Get the average of marks in MongoDB with aggregate?
- How to calculate a sum of specific documents using MongoDB aggregation?
- How to compare two fields in aggregation filter with MongoDB?
- MongoDB query to get documents with multiple conditions set in $or?
- MongoDB aggregation with multiple keys
- MongoDB query to replace value with aggregation?
- How to use $ifNull with MongoDB aggregation?
- MongoDB aggregation to sum individual properties on an object in an array across documents

Advertisements