- Reference >
- Operators >
- Query Modifiers >
- $natural
$natural¶
Definition¶
- $natural¶
Use the $natural operator to use natural order for the results of a sort operation. Natural order refers to the logical ordering of documents internally within the database.
The $natural operator uses the following syntax to return documents in the order they exist on disk:
db.collection.find().sort( { $natural: 1 } )
Behavior¶
On a sharded collection the $natural operator returns a collection scan sorted in natural order, the order the database inserts and stores documents on disk.
You cannot specify $natural sort order if the query includes a $text expression.
Examples¶
Reverse Order¶
Use -1 to return documents in the reverse order as they occur on disk:
db.collection.find().sort( { $natural: -1 } )
Natural Order Comparison¶
To demonstrate natural ordering:
Create an { normal: 1 } index on a collection (e.g. coll).
Insert relevant objects with _id and normal values, for example, a document with _id and normal fields that both hold the same string:
db.coll.insert( { _id: "01", normal: "01" } )
Use values with different types for each document, but both fields in the document should have the same value:
Use .find().sort().explain() for all operations.
This scenario returns these results when using find() for different _id values; sorting with the $natural operator, _id index, and normal index; and a description of the explain() method output:
| sort() | |||
|---|---|---|---|
| find() | $natural:1 | _id:1 | normal:1 |
| _id:ObjectId() | explain() used B-Tree cursor | explain() used B-Tree cursor | explain() used B-Tree cursor |
| _id:Object() | explain() used B-Tree cursor | explain() used B-Tree cursor | explain() used B-Tree cursor |
| _id:string() | explain() used B-Tree cursor | explain() used B-Tree cursor | explain() used B-Tree cursor |
| _id:integer() | explain() used B-Tree cursor | explain() used B-Tree cursor | explain() used B-Tree cursor |
| _id:BinData() | explain() scanned entire collection | explain() used B-Tree cursor | explain() used B-Tree cursor |
| normal:(any query) | explain() scanned entire collection | explain() used B-Tree cursor | explain() used B-Tree cursor |