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
Can I query on a MongoDB index if my query contains the $or operator?
Yes, you can query on MongoDB indexes with the $or operator. MongoDB can effectively use separate indexes for each condition in the $or query, combining results through an OR stage in the execution plan.
Syntax
db.collection.find({ $or: [
{ field1: value1 },
{ field2: value2 }
]}).explain();
Create Sample Indexes
First, create indexes on the fields you'll query ?
db.indexOrQueryDemo.createIndex({"First": 1});
{
"createdCollectionAutomatically": false,
"numIndexesBefore": 2,
"numIndexesAfter": 3,
"ok": 1
}
db.indexOrQueryDemo.createIndex({"Second": 1});
{
"createdCollectionAutomatically": false,
"numIndexesBefore": 3,
"numIndexesAfter": 4,
"ok": 1
}
Query with $or and Explain Plan
Now query using $or operator and analyze the execution plan ?
db.indexOrQueryDemo.find({$or: [{First: 1}, {Second: 2}]}).explain();
{
"queryPlanner": {
"plannerVersion": 1,
"namespace": "test.indexOrQueryDemo",
"winningPlan": {
"stage": "SUBPLAN",
"inputStage": {
"stage": "FETCH",
"inputStage": {
"stage": "OR",
"inputStages": [
{
"stage": "IXSCAN",
"keyPattern": {"First": 1},
"indexName": "First_1",
"indexBounds": {
"First": ["[1.0, 1.0]"]
}
},
{
"stage": "IXSCAN",
"keyPattern": {"Second": 1},
"indexName": "Second_1",
"indexBounds": {
"Second": ["[2.0, 2.0]"]
}
}
]
}
}
}
},
"ok": 1
}
How It Works
The execution plan shows MongoDB uses both indexes effectively:
- OR stage: Combines results from multiple index scans
- IXSCAN: Each condition uses its respective index (First_1 and Second_1)
- FETCH: Retrieves full documents after index filtering
Conclusion
MongoDB efficiently supports $or queries with indexes by using separate index scans for each condition and combining results. The explain() method confirms index usage through the OR execution stage.
Advertisements
