'MongoDB chooses the wrong index
I have a MongoDB collection called test with the following two simple documents:
{
"first_name" : "John",
"last_name" : "Smith",
"age" : 25
}
{
"first_name" : "James",
"last_name" : "Bond",
"age" : 31
}
I also created the following indexes for this collection:
{
"first_name" : 1
}
{
"last_name" : 1
}
{
"age" : 1
}
{
"first_name" : 1,
"last_name" : 1,
"age" : 1
}
The following queries use their corresponded field index:
db.getCollection('test').find({first_name: 'John'});
db.getCollection('test').find({last_name: 'Smith'});
db.getCollection('test').find({age: 25});
But when I perform the following query:
db.getCollection('test').find({first_name: 'John', last_name: 'Smith', age: 25});
It uses the single index for the field last_name, instead of the compound index that includes all three fields.
Any ideas/references on this issue?
MongoDB version: 3.0.7
Thanks
Solution 1:[1]
It seems that the order of defining the indexes is also effective in selecting it, for example :
{
"first_name" : 1,
"last_name" : 1,
"age" : 1
}
{
"first_name" : 1
}
{
"last_name" : 1
}
{
"age" : 1
}
also you can use Partial Indexes
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

