when to index on multiple keys in mongodb
say I have an Item document with :price and :qty fields. I sometimes want to find all documents matching a given :price AND :qty, and at other times it will be either :price on its own or :qty on its own.
I have already indexed the :price an开发者_如何学运维d :qty keys, but do I also need to create a compound index on both together or are the single key indexes enough?
Edit: I found this article on the mongodb site very useful:
http://www.mongodb.org/display/DOCS/Indexing+Advice+and+FAQ
An index on price
helps with queries on price
. An index on qty
helps with queries on qty
. An index on price
and qty
helps with queries on price
AND queries on price
and qty
. So, it's like getting two indexes for the price of one. It will not help for queries on qty
, though.
You should minimize the number of indexes you have, so drop one of your single-key indexes and create a compound index starting with that key.
As a general rule, if you're doing a query on x
, y
, and z
, you should have an index like {x:1, y:1, z:1}
. This index will make the following queries fast:
db.foo.find({x : ..., y : ..., z : ...})
db.foo.find({x : ..., y : ...})
db.foo.find({x : ...})
It will not make these queries fast:
db.foo.find({y : ..., z : ...})
db.foo.find({y : ...})
So, make sure your query has the starting key(s) of an index in it.
if you need :price on its own or :qty on its own then a compound index won't work.
精彩评论