Querying and adding Index to Mongo DB is a bit straight forward. But to use both together to optimize the response time can be a bit tricky.
As adding Index, can help to reduce to response time to find an item, similarly adding unwanted index can lead to other memory and response time-related issue.
So below are some quick rules/suggestion which should be followed to avoid any pitfalls of indexing
- If you have a field X on which you have an index with a unique key constraint. Then you don't have to have any other index with other fields along with this X field.
e.g
Then there is no point of having index like:
2. If you have a compound index and you want to use this index in your query then make sure your query being fired always have the first element of the index.
e.g
Then you can fire any query having the FIRST element (w) to use the index.
All above query will use the compound index defined above.
But you CAN'T fire any query which does not have the first element of the indexed as it won't use the index.
e.g
For more info read : compound-index and index-intersection-compound-indexes
3. You should always check your index and write query against it and not to do vise-verse. If there is no index to cater your query first add the index and then make the query against it.
No comments:
Post a Comment