MongoDB Indexes

Indexes are the subject of week 4 of MongoDB University. Don’t worry the weeks between 1 and 4 will come along 😉

Indexes are the single most important factor in database performance. Having no indexes or indexes on the wrong fields can make your application extreme slow.

Creating indexes

Creating indexes in mongoDB is easy and can be done using the ensureIndex() function.

# this creates an index on the field student_id in the scores collection
db.scores.ensureIndex({'student_id': 1})

# this creates an index on the field isbn and price in the books collection
db.books.ensureIndex({'isbn': 1, 'price': 1})

Dropping indexes

Dropping indexes is just as easy as creating ones.

# drop index on 'isbn' field
db.books.dropIndex({'isbn':1})

Discovering indexes

Discovering indexes in MySQL can be done using the “SHOW INDEX” syntax. In MongoDB you can use the following command to find the indexes of the current used database.

# this find will list the indexes of the current used database
db.systems.indexes.find()

Another way to find indexes inside a collection is to use the function getIndexes()

# display indexes of "books  collection
db.books.getIndexes()

Unique indexes

Just like MySQL (and probably any other relational database) MongoDB supports unique indexes on the fields of a collection. Creating an unique index on a field is done using by adding “unique: true” to the ensureIndex() function.

# example of adding unique index on isbn field
db.books.ensureIndex({'isbn': 1}, {unique: true})

Sparse indexes

Sparse indexes only contain entries for documents that have the indexed field, even if the index field contains a null value. The index skips over any document that is missing the indexed field.

Creating sparse indexes example:

# example of adding sparse index
db.books.ensureIndex({'isbn': 1}, {sparse: true})

WARNING! – use this option with care, because it skips any document that is missing the indexed field

Removing duplicates

Sometimes when you want to add an unique index on a field, the creation of the index fails because there are duplicate values.  For this reason MongoDB has the option “dropDups”. When you the option “dropDups” is added when you create an index all the duplicate values are being deleted by MongoDB.

# example of adding dropDups
db.books.ensureIndex({'isbn': 1}, {unique: true, dropDups: true})

Multikey indexes

Geospatial indexes

Spherical indexes

 

Geef een reactie

Het e-mailadres wordt niet gepubliceerd. Verplichte velden zijn gemarkeerd met *