Sort MongoDB documents in descending order


To sort documents, use sort() along with find(). Let us create a collection with documents −

> db.demo630.insertOne({"Value":10});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9b080e6c954c74be91e6ba")
}
> db.demo630.insertOne({"Value":200});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9b08116c954c74be91e6bb")
}
> db.demo630.insertOne({"Value":40});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9b08146c954c74be91e6bc")
}
> db.demo630.insertOne({"Value":60});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9b08176c954c74be91e6bd")
}

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

> db.demo630.find();

This will produce the following output −

{ "_id" : ObjectId("5e9b080e6c954c74be91e6ba"), "Value" : 10 }
{ "_id" : ObjectId("5e9b08116c954c74be91e6bb"), "Value" : 200 }
{ "_id" : ObjectId("5e9b08146c954c74be91e6bc"), "Value" : 40 }
{ "_id" : ObjectId("5e9b08176c954c74be91e6bd"), "Value" : 60 }

Following is the query to sort −

> db.demo630.find().sort({Value:-1});

This will produce the following output −

{ "_id" : ObjectId("5e9b08116c954c74be91e6bb"), "Value" : 200 }
{ "_id" : ObjectId("5e9b08176c954c74be91e6bd"), "Value" : 60 }
{ "_id" : ObjectId("5e9b08146c954c74be91e6bc"), "Value" : 40 }
{ "_id" : ObjectId("5e9b080e6c954c74be91e6ba"), "Value" : 10 }

Updated on: 12-May-2020

211 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements