Sort and Group in one MongoDB aggregation query?


For sorting and grouping in a single query, use the $group operator along with aggregate framework. Let us first create a collection with documents −

> db.sortAndGroupDemo.insertOne({
   Price :40,
   Product: 10
});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce8f2bc78f00858fb12e907")
}
> db.sortAndGroupDemo.insertOne({
   Price :100,
   Product: 10
});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce8f2bc78f00858fb12e908")
}
> db.sortAndGroupDemo.insertOne({
   Price :90,
   Product: 20
});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce8f2bc78f00858fb12e909")
}
> db.sortAndGroupDemo.insertOne({
   Price :200,
   Product: 10
});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce8f2bc78f00858fb12e90a")
}
> db.sortAndGroupDemo.insertOne({
   Price :70,
   Product: 20
});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce8f2bc78f00858fb12e90b")
}
> db.sortAndGroupDemo.insertOne({
   Price :70,
   Product: 30
});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce8f2bd78f00858fb12e90c")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.sortAndGroupDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5ce8f2bc78f00858fb12e907"),
   "Price" : 40,
   "Product" : 10
}
{
   "_id" : ObjectId("5ce8f2bc78f00858fb12e908"),
   "Price" : 100,
   "Product" : 10
}
{
   "_id" : ObjectId("5ce8f2bc78f00858fb12e909"),
   "Price" : 90,
   "Product" : 20
}
{
   "_id" : ObjectId("5ce8f2bc78f00858fb12e90a"),
   "Price" : 200,
   "Product" : 10
}
{
   "_id" : ObjectId("5ce8f2bc78f00858fb12e90b"),
   "Price" : 70,
   "Product" : 20
}
{
   "_id" : ObjectId("5ce8f2bd78f00858fb12e90c"),
   "Price" : 70,
   "Product" : 30
}

Following is the query to sort and group in a single MongoDB aggregation query −

> db.sortAndGroupDemo.aggregate(
   [
      { "$group": { "_id": "$Product" }},
      { "$sort" : { "Price": 1 }},
      { "$project":{"_id":1 }}
   ]
);

This will produce the following output −

{ "_id" : 30 }
{ "_id" : 20 }
{ "_id" : 10 }

Updated on: 30-Jul-2019

535 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements