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
How does MongoDB order their docs in one collection?
MongoDB orders documents in a collection using the $natural operator, which returns documents in their natural insertion order. By default, find() returns documents in the order they were inserted into the collection.
Syntax
db.collection.find().sort({ "$natural": 1 });
Where 1 for ascending (insertion order) and -1 for descending (reverse insertion order).
Sample Data
Let us create a collection with sample documents ?
db.orderDocsDemo.insertMany([
{"UserScore": 87},
{"UserScore": 98},
{"UserScore": 99},
{"UserScore": 67},
{"UserScore": 78},
{"UserScore": 91},
{"UserScore": 86}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c9531a316f542d757e2b44b"),
ObjectId("5c9531a816f542d757e2b44c"),
ObjectId("5c9531b216f542d757e2b44d"),
ObjectId("5c9531b716f542d757e2b44e"),
ObjectId("5c9531bd16f542d757e2b44f"),
ObjectId("5c9531c416f542d757e2b450"),
ObjectId("5c9531c816f542d757e2b451")
]
}
Example 1: Natural Order (Default)
Display documents in their natural insertion order ?
db.orderDocsDemo.find().sort({ "$natural": 1 });
{ "_id": ObjectId("5c9531a316f542d757e2b44b"), "UserScore": 87 }
{ "_id": ObjectId("5c9531a816f542d757e2b44c"), "UserScore": 98 }
{ "_id": ObjectId("5c9531b216f542d757e2b44d"), "UserScore": 99 }
{ "_id": ObjectId("5c9531b716f542d757e2b44e"), "UserScore": 67 }
{ "_id": ObjectId("5c9531bd16f542d757e2b44f"), "UserScore": 78 }
{ "_id": ObjectId("5c9531c416f542d757e2b450"), "UserScore": 91 }
{ "_id": ObjectId("5c9531c816f542d757e2b451"), "UserScore": 86 }
Notice documents are returned exactly in the order they were inserted.
Example 2: Field-Based Sorting
Sort documents by UserScore in ascending order ?
db.orderDocsDemo.find().sort({ "UserScore": 1 });
{ "_id": ObjectId("5c9531b716f542d757e2b44e"), "UserScore": 67 }
{ "_id": ObjectId("5c9531bd16f542d757e2b44f"), "UserScore": 78 }
{ "_id": ObjectId("5c9531c816f542d757e2b451"), "UserScore": 86 }
{ "_id": ObjectId("5c9531a316f542d757e2b44b"), "UserScore": 87 }
{ "_id": ObjectId("5c9531c416f542d757e2b450"), "UserScore": 91 }
{ "_id": ObjectId("5c9531a816f542d757e2b44c"), "UserScore": 98 }
{ "_id": ObjectId("5c9531b216f542d757e2b44d"), "UserScore": 99 }
Key Points
-
$natural: 1returns documents in insertion order -
$natural: -1returns documents in reverse insertion order - Without explicit sorting,
find()uses natural order by default - Field-based sorting overrides natural order
Conclusion
MongoDB uses the $natural operator to maintain document order based on insertion sequence. This provides predictable ordering when no explicit sort criteria is specified, ensuring documents are retrieved in the same order they were added to the collection.
