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 to force MongoDB to use the BasicCursor instead of an index?
To force MongoDB to use a BasicCursor instead of an index, use the hint() method with $natural: 1. This bypasses any existing indexes and performs a collection scan in natural document order.
Syntax
db.collection.find(query).hint({ $natural: 1 });
Create Sample Data
First, let's create an index and insert some test documents ?
db.demo31.createIndex({"StudentFirstName": 1});
{
"createdCollectionAutomatically": true,
"numIndexesBefore": 1,
"numIndexesAfter": 2,
"ok": 1
}
db.demo31.insertMany([
{"StudentFirstName": "John"},
{"StudentFirstName": "Jace"},
{"StudentFirstName": "Chris"},
{"StudentFirstName": "James"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e174f8fcfb11e5c34d898c1"),
ObjectId("5e174f97cfb11e5c34d898c2"),
ObjectId("5e174f9ccfb11e5c34d898c3"),
ObjectId("5e174fa0cfb11e5c34d898c4")
]
}
Example: Force BasicCursor Usage
Query for students whose names start with "Ja" using BasicCursor instead of the index ?
db.demo31.find({"StudentFirstName": {$regex: '^Ja'}}).hint({ $natural: 1});
{ "_id": ObjectId("5e174f97cfb11e5c34d898c2"), "StudentFirstName": "Jace" }
{ "_id": ObjectId("5e174fa0cfb11e5c34d898c4"), "StudentFirstName": "James" }
Verify Collection Scan
Use explain() to confirm MongoDB is performing a collection scan ?
db.demo31.find({"StudentFirstName": {$regex: '^Ja'}}).hint({ $natural: 1}).explain("executionStats");
Key Points
-
hint({ $natural: 1 })forces a collection scan in insertion order - Use
$natural: -1to scan in reverse insertion order - BasicCursor is slower than indexes but useful for testing or specific scenarios
Conclusion
The hint({ $natural: 1 }) method forces MongoDB to use BasicCursor for collection scanning instead of available indexes. This bypasses index optimization and scans documents in their natural storage order.
Advertisements
