Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
MongoDB aggregate query to sort
The $sort stage in MongoDB aggregation pipeline sorts documents by one or more fields. Use 1 for ascending order and -1 for descending order. You can combine it with other stages like $match to filter and sort results.
Syntax
db.collection.aggregate([
{ $match: { field: value } },
{ $sort: { field: 1 } } // 1 for ascending, -1 for descending
]);
Sample Data
db.demo67.insertMany([
{ "StudentAge": 23 },
{ "StudentAge": 21 },
{ "StudentAge": 24 }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e289edf602d9a2ff1828ed8"),
ObjectId("5e289ee1602d9a2ff1828ed9"),
ObjectId("5e289ee3602d9a2ff1828eda")
]
}
Example 1: Sort in Descending Order
Filter students older than 20 and sort by age in descending order ?
db.demo67.aggregate([
{ $match: { "StudentAge": { $gt: 20 } } },
{ $sort: { "StudentAge": -1 } }
]);
{ "_id": ObjectId("5e289ee3602d9a2ff1828eda"), "StudentAge": 24 }
{ "_id": ObjectId("5e289edf602d9a2ff1828ed8"), "StudentAge": 23 }
{ "_id": ObjectId("5e289ee1602d9a2ff1828ed9"), "StudentAge": 21 }
Example 2: Sort in Ascending Order
Sort all students by age in ascending order ?
db.demo67.aggregate([
{ $sort: { "StudentAge": 1 } }
]);
{ "_id": ObjectId("5e289ee1602d9a2ff1828ed9"), "StudentAge": 21 }
{ "_id": ObjectId("5e289edf602d9a2ff1828ed8"), "StudentAge": 23 }
{ "_id": ObjectId("5e289ee3602d9a2ff1828eda"), "StudentAge": 24 }
Key Points
-
$sortcan be used with or without$matchfiltering - Use
1for ascending order and-1for descending order - Sort operations are performed after filtering when combined with
$match
Conclusion
The $sort stage in MongoDB aggregation pipeline effectively sorts documents by specified fields. Combine it with $match to filter and sort results in a single query operation.
Advertisements
