Database Reference
In-Depth Information
Building Indexes
As mentioned in Chapter 1, an index is nothing more than a data structure that collects
information about the values of specified fields in the documents of a collection. This
data structure is used by MongoDB's query optimizer to quickly sort through and order
the documents in a collection.
Remember that indexing ensures a quick lookup from data in your documents.
Basically, you should view an index as a predefined query that was executed and had its
results stored. As you can imagine, this enhances query-performance dramatically. The
general rule of thumb in MongoDB is that you should create an index for the same sort of
scenarios where you would want to have an index in MySQL.
The biggest benefit of creating your own indexes is that querying for often-used
information will be incredibly fast because your query won't need to go through your
entire database to collect this information.
Creating (or deleting) an index is relatively easy—once you get the hang of it, anyway.
You will learn how to do so in Chapter 4, which covers working with data. You will also
learn some more advanced techniques for taking advantage of indexing in Chapter 10,
which covers how to maximize performance.
Impacting Performance with Indexes
You might wonder why you would ever need to delete an index, rebuild your indexes, or
even delete all indexes within a collection. The simple answer is that doing so lets you
clean up some irregularities. For instance, sometimes the size of a database can increase
dramatically for no apparent reason. At other times, the space used by the indexes might
strike you as excessive.
Another good thing to keep in mind: you can have a maximum of 64 indexes per
collection. Generally speaking, this is far more than you should need, but you could
potentially hit this limit someday.
adding an index increases query speed, but it reduces insertion or deletion speed.
It's best to consider only adding indexes for collections where the number of reads is higher
than the number of writes. When more writes occur than reads, indexes may even prove to
be counterproductive.
Note
Finally, all index information is stored in the system.indexes collection in your
database. For example, you can run the db.system.indexes.find() command to take
a quick peek at the indexes that have been stored so far. To see the indexes created for a
specific collection, you can use the getIndexes command:
db.collection.getIndexes()
 
 
Search WWH ::




Custom Search