Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
What is ({$natural: 1}) in MongoDB?
The {$natural: 1} is a MongoDB sort option that returns documents in their natural insertion order. When used with {$natural: -1}, it works like LIFO (Last In First Out), showing the most recently inserted document first.
Syntax
db.collection.find().sort({$natural: 1}); // Insertion order
db.collection.find().sort({$natural: -1}); // Reverse insertion order
Sample Data
Let us create a collection with documents ?
db.demo614.insertMany([
{"CountryName": "US"},
{"CountryName": "UK"},
{"CountryName": "AUS"},
{"CountryName": "IND"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e988cddf6b89257f5584d8e"),
ObjectId("5e988ce0f6b89257f5584d8f"),
ObjectId("5e988ce3f6b89257f5584d90"),
ObjectId("5e988cebf6b89257f5584d91")
]
}
Example 1: Natural Order ({$natural: 1})
Display documents in their natural insertion order ?
db.demo614.find().sort({$natural: 1});
{ "_id": ObjectId("5e988cddf6b89257f5584d8e"), "CountryName": "US" }
{ "_id": ObjectId("5e988ce0f6b89257f5584d8f"), "CountryName": "UK" }
{ "_id": ObjectId("5e988ce3f6b89257f5584d90"), "CountryName": "AUS" }
{ "_id": ObjectId("5e988cebf6b89257f5584d91"), "CountryName": "IND" }
Example 2: Reverse Natural Order ({$natural: -1})
Display documents in reverse insertion order (LIFO) ?
db.demo614.find().sort({$natural: -1});
{ "_id": ObjectId("5e988cebf6b89257f5584d91"), "CountryName": "IND" }
{ "_id": ObjectId("5e988ce3f6b89257f5584d90"), "CountryName": "AUS" }
{ "_id": ObjectId("5e988ce0f6b89257f5584d8f"), "CountryName": "UK" }
{ "_id": ObjectId("5e988cddf6b89257f5584d8e"), "CountryName": "US" }
Key Points
-
{$natural: 1}returns documents in the order they were inserted -
{$natural: -1}returns documents in reverse insertion order - This sort method is useful for time-based queries when you need chronological ordering
Conclusion
The $natural sort option provides an efficient way to retrieve documents based on their insertion order. Use -1 for LIFO behavior to get the most recent documents first.
Advertisements
