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
Sort the MongoDB documents in ascending order with aggregation?
To sort MongoDB documents in ascending order with aggregation, use the $sort stage in the aggregation pipeline with field: 1 (ascending) or field: -1 (descending).
Syntax
db.collection.aggregate([
{ $sort: { fieldName: 1 } } // 1 for ascending, -1 for descending
]);
Sample Data
db.demo652.insertMany([
{
value: 10,
"details": [
{
"ProductName": "Product-1",
"ProductQuantity": 8,
"ProductPrice": 500
},
{
"ProductName": "Product-2",
"ProductQuantity": 7,
"ProductPrice": 500
}
]
},
{
value: 5,
"details": [
{
"ProductName": "Product-1",
"ProductQuantity": 8,
"ProductPrice": 500
},
{
"ProductName": "Product-2",
"ProductQuantity": 7,
"ProductPrice": 500
}
]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e9f0730e3c3cd0dcff36a62"),
ObjectId("5e9f0740e3c3cd0dcff36a63")
]
}
Example: Sort by Value Field
Sort the documents by the value field in ascending order using aggregation ?
db.demo652.aggregate([
{ $unwind: "$details" },
{ $match: {} },
{
$group: {
"ProductPrice": {
"$first": "$value"
},
"details": {
"$push": {
"ProductName": "$details.ProductName"
}
},
"_id": "$_id"
}
},
{
$sort: {
"ProductPrice": 1
}
},
{
$project: {
"_id": 0,
"ProductPrice": 1,
"details": 1
}
}
]);
{
"ProductPrice": 5,
"details": [
{
"ProductName": "Product-1"
},
{
"ProductName": "Product-2"
}
]
}
{
"ProductPrice": 10,
"details": [
{
"ProductName": "Product-1"
},
{
"ProductName": "Product-2"
}
]
}
Key Points
- Use
$sort: { field: 1 }for ascending order and{ field: -1 }for descending order. - Place
$sortstage after any grouping operations for better performance. - Multiple fields can be sorted:
{ field1: 1, field2: -1 }.
Conclusion
The $sort stage in MongoDB aggregation pipeline sorts documents by specified fields. Use 1 for ascending and -1 for descending order to organize your query results effectively.
Advertisements
