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
How do I sort natural in MongoDB?
Use $natural to sort documents in MongoDB by their natural order (the order they were inserted into the database). This operator sorts documents based on their physical storage order on disk.
Syntax
db.collection.find().sort({ $natural: 1 }) // Ascending (insertion order)
db.collection.find().sort({ $natural: -1 }) // Descending (reverse insertion order)
Sample Data
Let us create a collection with documents ?
db.demo684.insertMany([
{Value: 10},
{Value: 50},
{Value: 60},
{Value: 40}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5ea530cea7e81adc6a0b3957"),
ObjectId("5ea530d1a7e81adc6a0b3958"),
ObjectId("5ea530d4a7e81adc6a0b3959"),
ObjectId("5ea530d8a7e81adc6a0b395a")
]
}
Display all documents from the collection ?
db.demo684.find();
{ "_id": ObjectId("5ea530cea7e81adc6a0b3957"), "Value": 10 }
{ "_id": ObjectId("5ea530d1a7e81adc6a0b3958"), "Value": 50 }
{ "_id": ObjectId("5ea530d4a7e81adc6a0b3959"), "Value": 60 }
{ "_id": ObjectId("5ea530d8a7e81adc6a0b395a"), "Value": 40 }
Example 1: Natural Sort Ascending
Sort documents in natural order (insertion order) ?
db.demo684.find().sort({ $natural: 1 });
{ "_id": ObjectId("5ea530cea7e81adc6a0b3957"), "Value": 10 }
{ "_id": ObjectId("5ea530d1a7e81adc6a0b3958"), "Value": 50 }
{ "_id": ObjectId("5ea530d4a7e81adc6a0b3959"), "Value": 60 }
{ "_id": ObjectId("5ea530d8a7e81adc6a0b395a"), "Value": 40 }
Example 2: Natural Sort Descending
Sort documents in reverse insertion order ?
db.demo684.find().sort({ $natural: -1 });
{ "_id": ObjectId("5ea530d8a7e81adc6a0b395a"), "Value": 40 }
{ "_id": ObjectId("5ea530d4a7e81adc6a0b3959"), "Value": 60 }
{ "_id": ObjectId("5ea530d1a7e81adc6a0b3958"), "Value": 50 }
{ "_id": ObjectId("5ea530cea7e81adc6a0b3957"), "Value": 10 }
Key Points
-
$natural: 1sorts in insertion order (oldest first) -
$natural: -1sorts in reverse insertion order (newest first) - Natural sort reflects the physical storage order on disk
- Cannot be combined with other sort criteria
Conclusion
The $natural operator provides a simple way to sort MongoDB documents by their insertion order. Use 1 for ascending (oldest first) and -1 for descending (newest first) natural sorting.
Advertisements
