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
Sort id and reverse the items with MongoDB
The $natural operator returns documents in natural insertion order. To reverse the items and get them in reverse insertion order, use $natural:-1 with the sort() method.
Syntax
db.collection.find().sort({$natural: -1});
Sample Data
Let us create a collection with documents ?
db.demo710.insertMany([
{id: 101, Name: "Robert"},
{id: 102, Name: "Carol"},
{id: 103, Name: "Mike"},
{id: 104, Name: "Sam"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5ea83a855d33e20ed1097b7a"),
ObjectId("5ea83a8d5d33e20ed1097b7b"),
ObjectId("5ea83a935d33e20ed1097b7c"),
ObjectId("5ea83a9b5d33e20ed1097b7d")
]
}
Example 1: Display Documents in Natural Order
Display all documents in their natural insertion order ?
db.demo710.find();
{"_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"}
Example 2: Reverse Items Using $natural
Sort and reverse the items using $natural:-1 ?
db.demo710.find().sort({$natural: -1});
{"_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"}
Key Points
-
$natural: 1returns documents in natural insertion order (default behavior) -
$natural: -1reverses the natural order, showing most recently inserted documents first - This is useful when you want to retrieve documents in reverse chronological order without sorting by a specific field
Conclusion
Use sort({$natural: -1}) to reverse the natural insertion order of documents in MongoDB. This provides a simple way to get the most recently inserted documents first without needing additional sorting criteria.
Advertisements
