Indexing in MongoDB
Recall that an index on a database field is a tree structure that greatly increases the efficiency of queries on that field. In Chapter 5, Relational Databases, we described the B-tree data structure (see Figure 5-18) that is the common mechanism for implementing database indexes.
Like relational database systems, Mongo also supports indexing. As an example, suppose that our books collection contains 1,000,000 documents, one for each book. Further, suppose that this query is executed:
db.books.find({year:{"$gte":1924,"$lt":1930}})This would list all books published from 1924 to 1930. If the year filed is indexed, the response would be instantaneous. Otherwise, every one of the 1,000,000 documents would have to be examined.
The required _id field in each collection is indexed automatically. This is a unique index, which means that it prevents the insertion of any document with the same _id value as one already in the collection.
To index any other field, use the db.collection...
 
                                             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
     
         
                 
                 
                 
                 
                 
                 
                 
                 
                 
                 
                 
                 
                