- 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 query on top N rows in MongoDB?
To query on top N rows in MongoDB, you can use aggregate framework. Let us create a collection with documents
> db.topNRowsDemo.insertOne({"StudentName":"Larry","Score":78}); { "acknowledged" : true, "insertedId" : ObjectId("5ca26eee6304881c5ce84b91") } > db.topNRowsDemo.insertOne({"StudentName":"Chris","Score":45}); { "acknowledged" : true, "insertedId" : ObjectId("5ca26ef66304881c5ce84b92") } > db.topNRowsDemo.insertOne({"StudentName":"Mike","Score":65}); { "acknowledged" : true, "insertedId" : ObjectId("5ca26efe6304881c5ce84b93") } > db.topNRowsDemo.insertOne({"StudentName":"Adam","Score":55}); { "acknowledged" : true, "insertedId" : ObjectId("5ca26f066304881c5ce84b94") } > db.topNRowsDemo.insertOne({"StudentName":"John","Score":86}); { "acknowledged" : true, "insertedId" : ObjectId("5ca26f0f6304881c5ce84b95") }
Following is the query to display all documents from a collection with the help of find() method
> db.topNRowsDemo.find().pretty();
This will produce the following output
{ "_id" : ObjectId("5ca26eee6304881c5ce84b91"), "StudentName" : "Larry", "Score" : 78 } { "_id" : ObjectId("5ca26ef66304881c5ce84b92"), "StudentName" : "Chris", "Score" : 45 } { "_id" : ObjectId("5ca26efe6304881c5ce84b93"), "StudentName" : "Mike", "Score" : 65 } { "_id" : ObjectId("5ca26f066304881c5ce84b94"), "StudentName" : "Adam", "Score" : 55 } { "_id" : ObjectId("5ca26f0f6304881c5ce84b95"), "StudentName" : "John", "Score" : 86 }
Here is how you can query on top N rows in MongoDB
> db.topNRowsDemo.aggregate([ ... {$sort: {StudentName: 1}}, ... {$limit: 5}, ... {$match: {Score: {$gt: 65}}} ... ]).pretty();
This will produce the following output
{ "_id" : ObjectId("5ca26f0f6304881c5ce84b95"), "StudentName" : "John", "Score" : 86 } { "_id" : ObjectId("5ca26eee6304881c5ce84b91"), "StudentName" : "Larry", "Score" : 78 }
Advertisements