Reputation: 20080
In a collection where entries look like the following:
{
"a": {
"b": {
"c": "myValue"
}
},
"f" : 14000000000
}
We have created an composite index like so:
{
"a" : 1,
"a.b" : 1,
"a.b.c" : 1,
"f" : 1
}
However, when we run the following query:
{
"a": {
"b": {
"c": "myValue"
}
},
"f" : { $gt: 1300000}
}
This doesn't use any index. How should indexes be defined on MongoDB objects (note we are not trying to have an index on a.b.c but on the whole object a)
Upvotes: 2
Views: 44
Reputation: 20080
We have discovered that if you want to take advantage of indexes, your queries need to be flattened on the fields where the index are:
{
"a.b.c": "myValue",
"f" : { $gt: 1300000}
}
Will actually use the index. Therefore, if you have the following case:
{
"a": {
"b": {
"c": "myValue",
"d": "myValue2"
}
},
"f" : { $gt: 1300000}
}
you should actually rewrite the query like so
{
"a.b.c": "myValue",
"a.b.d": "myValue2",
"f" : { $gt: 1300000}
}
Upvotes: 2
Reputation: 4558
From MongoDB documentation about indexes :
[...] The index stores the value of a specific field or set of fields, ordered by the value of the field. [...]
So I think you can't index a whole object or an embedded object. You can just index fields of an object.
Also, I think you're trying to do here is a Compound Index.
Did you try this index ?
{
"a.b.c" : 1,
"f" : 1
}
Finally, if you're using Replica Sets and/or Sharding, be aware that the behavior of the indexes is not the same :
I hope this will help you.
Upvotes: 1