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 and Group in one MongoDB aggregation query?
To sort and group documents in a single MongoDB aggregation query, use the $group and $sort operators within the aggregation pipeline. The order of these stages determines whether you sort before or after grouping.
Syntax
db.collection.aggregate([
{ $group: { _id: "$field", ... } },
{ $sort: { field: 1 } }
]);
Sample Data
db.sortAndGroupDemo.insertMany([
{ Price: 40, Product: 10 },
{ Price: 100, Product: 10 },
{ Price: 90, Product: 20 },
{ Price: 200, Product: 10 },
{ Price: 70, Product: 20 },
{ Price: 70, Product: 30 }
]);
Following is the query to display all documents from the collection ?
db.sortAndGroupDemo.find();
[
{ "_id": ObjectId("..."), "Price": 40, "Product": 10 },
{ "_id": ObjectId("..."), "Price": 100, "Product": 10 },
{ "_id": ObjectId("..."), "Price": 90, "Product": 20 },
{ "_id": ObjectId("..."), "Price": 200, "Product": 10 },
{ "_id": ObjectId("..."), "Price": 70, "Product": 20 },
{ "_id": ObjectId("..."), "Price": 70, "Product": 30 }
]
Example: Group by Product and Sort Results
Following is the query to group by Product and sort the grouped results ?
db.sortAndGroupDemo.aggregate([
{ $group: { _id: "$Product", totalPrice: { $sum: "$Price" } } },
{ $sort: { totalPrice: 1 } }
]);
[
{ "_id": 30, "totalPrice": 70 },
{ "_id": 20, "totalPrice": 160 },
{ "_id": 10, "totalPrice": 340 }
]
Key Points
- Use
$groupto group documents by a specific field and perform aggregation operations - Use
$sortafter grouping to sort the grouped results - The aggregation pipeline executes stages sequentially
Conclusion
Combine $group and $sort operators in the aggregation pipeline to group documents and sort results in a single query. The stage order determines the sorting behavior.
Advertisements
