Indexing documents in MongoDB
Friday, July 23, 2010 at 6:01AM |
Derek Stainer Whether you are working with a traditional relational database like MySQL or a NoSQL database like MongoDB, indexing plays a big part performing efficient lookups. Alberto Lerner, from 10gen, discusses how MongoDB indexes documents for fast retrieval.
MongoDB Indexing Basics:
- MongoDB can use separate tree structures to index a collection
- MongoDB is going to try an use an index to avoid going through a collection
Our job as developers is to provide MongoDB with indices on important queries. What makes an important query? Frequently used queries or queries where response time is critical. MongoDB provides us with an automatic index on _id. Others can be created with 'ensureIndex'.
When searching in MongoDB the search criteria is either the index key or the prefix of an index key. Searching can yield both exact matches or several results. There are a couple of special cases with indexing. For instance, null fields. In the case of null fields a value of null is stored in the index. In the case of fields that contain arrays, there will be one entry per element in that array.
Whenever, MongoDB evaluates search criteria only one index will be used. What if you have several indices, how does MongoDB decide? It uses previous executions, so it's a performance based selection process.
In the end, almost everything we do related to building applications revolves around trade-offs, and MongoDB is no different. Lerner reminds us that there is a trade-off that exists between search criteria performance and the insertion/updating/deletion of keys. So Lerner suggests as a concluding point to be "mindful of number of indexes and choice of keys".
10gen,
Alberto Lerner,
Indexing,
MongoDB 
