Reputation: 893
I'm new in mongoDb, And I don't understand when (and why) use ensureIndex
for example i have this collection
db.films.insert( { "Type" : "DVD", "Title" : "Matrix, The", "Released" :1999} )
db.films.insert( { "Type" : "DVD", "Title" : "Blade Runner", "Released" :1982 } )
db.films.insert( { "Type" : "DVD", "Title" : "Toy Story 3", "Released" :2010} )
if I try with
db.films.find(). min ( { Released: 1995 } ) . max ( { Released : 2005 } )
i have this error
error: {
"$err" : "no index found for specified keyPattern: {} min: { Released: 1995.0 } max: { Released: 2005.0 }",
"code" : 10367
}
I have to do
db.films.ensureIndex( { "Released": 1 } )
and all Works.
why this does not work?
db.films.find(). min ( { "Released": 1995 } ) . max ( { "Released" : 2005 } )
and when i have to use
. hint ( { Released : 1 } )
I try to do
db.films.ensureIndex( { "Released": 1 } )
db.films.ensureIndex( { "Released": -1 } )
and
db.films.find() . min ( { Released: 1995 } ) . max ( { Released : 2005 } ). hint ( { Released : -1 } )
this is my error
error: {
"$err" : "requested keyPattern does not match specified keys",
"code" : 10365
}
Upvotes: 0
Views: 236
Reputation: 43884
min()
and max()
are index operators. Instead of constrainng a set of results from an index by a range ($lt
, $lte
, $gt
and $gte
) they actually decide how much of the index is scanned by selecting a lower and upper limit of data points. You can see this most noticeably if you also do an explain()
.
Without an index MongoDB cannot restrict the index.
It should be noted that if you wish to go the route of using min
and max
then for descending indexes you will need to reverse the values within the two functions to match the reversed index.
In all honesty it is better to leave the range of index scanning to MongoDB most of the tme.
If your query:
db.films.find() . min ( { Released: 1995 } ) . max ( { Released : 2005 } ). hint ( { Released : -1 } )
Doesn't work it means that MongoDB cannot find the range you specify in your index.
Upvotes: 1
Reputation: 13015
Your query is not working because min() requires an index on a field and forces the query to use the index.
Upvotes: 1