Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is ({$natural: 1}) in MongoDB?
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" }Advertisements