What is ({$natural: 1}) in MongoDB?

MongoDBDatabaseBig Data Analytics

The ({$natural − 1}) works like LIFO(LAST IN FIRST OUT), that means last inserted document will be shown first.

Let us create a collection with documents −

> db.demo614.insertOne({"CountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e988cddf6b89257f5584d8e")
}
> db.demo614.insertOne({"CountryName":"UK"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e988ce0f6b89257f5584d8f")
}
> db.demo614.insertOne({"CountryName":"AUS"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e988ce3f6b89257f5584d90")
}
> db.demo614.insertOne({"CountryName":"IND"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e988cebf6b89257f5584d91")
}

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

> db.demo614.find();

This will produce the following output −

{ "_id" : ObjectId("5e988cddf6b89257f5584d8e"), "CountryName" : "US" }
{ "_id" : ObjectId("5e988ce0f6b89257f5584d8f"), "CountryName" : "UK" }
{ "_id" : ObjectId("5e988ce3f6b89257f5584d90"), "CountryName" : "AUS" }
{ "_id" : ObjectId("5e988cebf6b89257f5584d91"), "CountryName" : "IND" }

Following is the query to work with ({$natural: 1}) −

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

This will produce the following output −

{ "_id" : ObjectId("5e988cebf6b89257f5584d91"), "CountryName" : "IND" }
{ "_id" : ObjectId("5e988ce3f6b89257f5584d90"), "CountryName" : "AUS" }
{ "_id" : ObjectId("5e988ce0f6b89257f5584d8f"), "CountryName" : "UK" }
{ "_id" : ObjectId("5e988cddf6b89257f5584d8e"), "CountryName" : "US" }
raja
Published on 12-May-2020 10:07:10
Advertisements