|
Indexes enhance query performance, often dramatically. It's important to think about the kinds of queries your application will need so that you can define relevant indexes. Once that's done, actually creating the indexes in MongoDB is relatively easy. Indexes in MongoDB are conceptually similar to those in RDBMSes like MySQL. You will want an index in MongoDB in the same sort of situations where you would have wanted an index in MySQL. BasicsAn index is a data structure that collects information about the values of the specified fields in the documents of a collection. This data structure is used by Mongo's query optimizer to quickly sort through and order the documents in a collection. Formally speaking, these indexes are implemented as "B-Tree" indexes. In the shell, you can create an index by calling the ensureIndex() function, and providing a document that specifies one or more keys to index. Referring back to our examples database from Mongo Usage Basics, we can index on the 'j' field as follows: db.things.ensureIndex({j:1});
The ensureIndex() function only creates the index if it does not exist. Once a collection is indexed on a key, random access on query expressions which match the specified key are fast. Without the index, MongoDB has to go through each document checking the value of specified key in the query: db.things.find({j : 2}); // fast - uses index
db.things.find({x : 3}); // slow - has to check all because 'x' isn't indexed
Default IndexesAn index is always created on _id. This index is special and cannot be deleted. The _id index enforces uniqueness for its keys. Embedded KeysWith MongoDB you can even index on a key inside of an embedded document. For example: db.things.ensureIndex({"address.city": 1})
Documents as KeysIndexed fields may be of any type, including documents: db.factories.save( { name: "xyz", metro: { city: "New York", state: "NY" } } );
db.factories.ensureIndex( { metro : 1 } );
You may not as of yet specify a sort order for an object key; thus, at this time, object keys are useful for random access retrieval but less so for ordered access. (For the latter, consider using a compound key index.) Compound Keys IndexesIn addition to single-key basic indexes, MongoDB also supports multi-key "compound" indexes. Just like basic indexes, you use the ensureIndex() function in the shell to create the index, but instead of specifying only a single key, you can specify several : db.things.ensureIndex({j:1, name:-1});
When creating an index, the number associated with a key specifies the direction of the index, so it should always be 1 (ascending) or -1 (descending). Direction doesn't matter for single key indexes or for random access retrieval but is important if you are doing sorts or range queries on compound indexes. If you have a compound index on multiple fields, you can use it to query on the beginning subset of fields. So if you have an index on a,b,c you can use it query on a a,b a,b,c Unique IndexesMongoDB supports unique indexes, which guarantee that no documents are inserted whose values for the indexed keys match those of an existing document. To create an index that guarantees that no two documents have the same values for both firstname and lastname you would do: db.things.ensureIndex({firstname: 1, lastname: 1}, {unique: true});
Missing KeysWhen a document is saved to a collection with unique indexes, any missing indexed keys will be inserted with null values. Thus, it won't be possible to insert multiple documents missing the same indexed key. db.things.ensureIndex({firstname: 1}, {unique: true});
db.things.save({lastname: "Smith"});
// Next operation will fail because of the unique index on firstname.
db.things.save({lastname: "Jones"});
Duplicate ValuesA unique index cannot be created on a key that has duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate values, add the dropDups option. db.things.ensureIndex({firstname : 1}, {unique : true, dropDups : true})
Background Index BuildingBy default, building an index blocks other database operations. v1.3.2 and higher has a background index build option . Dropping IndexesTo delete all indexes on the specified collection: db.collection.dropIndexes(); To delete a single index: db.collection.dropIndex({x: 1, y: -1})
Running directly as a command without helper: // note: command was "deleteIndexes", not "dropIndexes", before MongoDB v1.3.2 // remove index with key pattern {y:1} from collection foo db.runCommand({dropIndexes:'foo', index : {y:1}}) // remove all indexes: db.runCommand({dropIndexes:'foo', index : '*'}) ReIndexThe reIndex command will rebuild all indexes for a collection. db.myCollection.reIndex()
// same as:
db.runCommand( { reIndex : 'myCollection' } )
Usually this is unnecessary. You may wish to do this if the size of your collection has changed dramatically or the disk space used by indexes seems oddly large. Repair database recreates all indexes in the database. Additional Notes on Indexes
Index PerformanceIndexes make retrieval by a key, including ordered sequential retrieval, very fast. Updates by key are faster too as MongoDB can find the document to update very quickly. However, keep in mind that each index created adds a certain amount of overhead for inserts and deletes. In addition to writing data to the base collection, keys must then be added to the B-Tree indexes. Thus, indexes are best for collections where the number of reads is much greater than the number of writes. For collections which are write-intensive, indexes, in some cases, may be counterproductive. Most collections are read-intensive, so indexes are a good thing in most situations. Using sort() without an IndexYou may use sort() to return data in order without an index if the data set to be returned is small (less than four megabytes). For these cases it is best to use limit() and sort() together. Geospatial
|

IF YOU HAVE A QUESTION, POST IT TO THE USER GROUP.
These pages are fine for comments, but for questions, your best bet will always be the MongoDB User Group. blog comments powered by Disqus