How to use MongoDB Aggregate to sort?


Use aggregate() and within that to sort, use $sort in MongoDB. Let us create a collection with documents −

> db.demo164.insertOne({"StudentAge":24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e36883d9e4f06af551997c8")
}
> db.demo164.insertOne({"StudentAge":25});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3688409e4f06af551997c9")
}
> db.demo164.insertOne({"StudentAge":22});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3688429e4f06af551997ca")
}
> db.demo164.insertOne({"StudentAge":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3688439e4f06af551997cb")
}

Display all documents from a collection with the help of find() method −

> db.demo164.find();

This will produce the following output −

{ "_id" : ObjectId("5e36883d9e4f06af551997c8"), "StudentAge" : 24 }
{ "_id" : ObjectId("5e3688409e4f06af551997c9"), "StudentAge" : 25 }
{ "_id" : ObjectId("5e3688429e4f06af551997ca"), "StudentAge" : 22 }
{ "_id" : ObjectId("5e3688439e4f06af551997cb"), "StudentAge" : 21 }

Here is the query to use MongoDB aggregate() −

> db.demo164.aggregate([{ $sort : { StudentAge : -1 } }]);

This will produce the following output −

{ "_id" : ObjectId("5e3688409e4f06af551997c9"), "StudentAge" : 25 }
{ "_id" : ObjectId("5e36883d9e4f06af551997c8"), "StudentAge" : 24 }
{ "_id" : ObjectId("5e3688429e4f06af551997ca"), "StudentAge" : 22 }
{ "_id" : ObjectId("5e3688439e4f06af551997cb"), "StudentAge" : 21 }

Updated on: 01-Apr-2020

114 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements