

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 aggregate query to sort
To sort, use $match along with aggregate. Let us create a collection with documents −
> db.demo67.insertOne({"StudentAge":23}); { "acknowledged" : true, "insertedId" : ObjectId("5e289edf602d9a2ff1828ed8") } > db.demo67.insertOne({"StudentAge":21}); { "acknowledged" : true, "insertedId" : ObjectId("5e289ee1602d9a2ff1828ed9") } > db.demo67.insertOne({"StudentAge":24}); { "acknowledged" : true, "insertedId" : ObjectId("5e289ee3602d9a2ff1828eda") }
Display all documents from a collection with the help of find() method −
> db.demo67.find();
This will produce the following output −
{ "_id" : ObjectId("5e289edf602d9a2ff1828ed8"), "StudentAge" : 23 } { "_id" : ObjectId("5e289ee1602d9a2ff1828ed9"), "StudentAge" : 21 } { "_id" : ObjectId("5e289ee3602d9a2ff1828eda"), "StudentAge" : 24 }
Following is the query to sort with aggregate in MongoDB −
> db.demo67.aggregate([ ... {$match: {"StudentAge": {$gt: 20} }} ... ,{$sort: {"StudentAge": -1} } ... ]);
This will produce the following output −
{ "_id" : ObjectId("5e289ee3602d9a2ff1828eda"), "StudentAge" : 24 } { "_id" : ObjectId("5e289edf602d9a2ff1828ed8"), "StudentAge" : 23 } { "_id" : ObjectId("5e289ee1602d9a2ff1828ed9"), "StudentAge" : 21 }
- Related Questions & Answers
- MongoDB query to implement aggregate function
- MongoDB query to aggregate nested array
- How to use MongoDB Aggregate to sort?
- MongoDB query to sort subdocuments
- MongoDB query to sort by words
- MongoDB query to sort nested array?
- How to sort, select and query subdocument in MongoDB?
- Sort and Group in one MongoDB aggregation query?
- Using $redact in MongoDB aggregate?
- Get substring in MongoDB aggregate
- MongoDB Aggregate group multiple result?
- How to aggregate array documents in MongoDB?
- How to update after aggregate in MongoDB?
- Sort array in MongoDB query and project all fields?
- Split a string during MongoDB aggregate
Advertisements