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 $group to group documents by a specific field and perform aggregation operations
  • Use $sort after 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.

Updated on: 2026-03-15T01:33:08+05:30

859 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements