Sort id and reverse the items with MongoDB


The $natural returns the documents in natural order. To reverse the items, use $natural:-1. Let us create a collection with documents −

> db.demo710.insertOne({id:101,Name:"Robert"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea83a855d33e20ed1097b7a")
}
> db.demo710.insertOne({id:102,Name:"Carol"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea83a8d5d33e20ed1097b7b")
}
> db.demo710.insertOne({id:103,Name:"Mike"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea83a935d33e20ed1097b7c")
}
> db.demo710.insertOne({id:104,Name:"Sam"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea83a9b5d33e20ed1097b7d")
}

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

> db.demo710.find();

This will produce the following output −

{ "_id" : ObjectId("5ea83a855d33e20ed1097b7a"), "id" : 101, "Name" : "Robert" }
{ "_id" : ObjectId("5ea83a8d5d33e20ed1097b7b"), "id" : 102, "Name" : "Carol" }
{ "_id" : ObjectId("5ea83a935d33e20ed1097b7c"), "id" : 103, "Name" : "Mike" }
{ "_id" : ObjectId("5ea83a9b5d33e20ed1097b7d"), "id" : 104, "Name" : "Sam" }

Following is the query to sort and reverse the items −

> db.demo710.find().sort({$natural:-1});

This will produce the following output −

{ "_id" : ObjectId("5ea83a9b5d33e20ed1097b7d"), "id" : 104, "Name" : "Sam" }
{ "_id" : ObjectId("5ea83a935d33e20ed1097b7c"), "id" : 103, "Name" : "Mike" }
{ "_id" : ObjectId("5ea83a8d5d33e20ed1097b7b"), "id" : 102, "Name" : "Carol" }
{ "_id" : ObjectId("5ea83a855d33e20ed1097b7a"), "id" : 101, "Name" : "Robert" }

Updated on: 14-May-2020

827 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements