Tuesday, 9 December 2014

Gain performance with Indexing in MongoDB

MongoDB Indexes

What is indexing?
Indexes provide high performance read operations for frequently used queries.For example Index in books it makes us to find the pages easily.

Index Introduction

Index supports the efficient execution of queries in mongoDB.With index,mongodb will scan only less documents in your collection.But without index it scans all the data in your documents and it takes so much time.


Index are special data structure that uses B-tree algorithm.

Indexes in mongodb are similar to the indexes in other database system like mysql,oracle etc.Mongodb defines indexes at the collection level and supports indexes on any field of the documents.

MongoDB can use the index to limit the number of documents

What is B-tree    ?

A B-tree is a method of placing and locating files in a database.B-tree algorithm minimizes the number of times a document must be accessed to locate a desired record, thereby speeding up the overall process.

Index Types

Mongodb provides a number of different types of indexes.In general, you should create indexes that support your common and user-facing queries. Having these indexes will ensure that MongoDB scans the smallest possible number of documents.

  • Single Field Indexes
  • Compound Indexes
  • Multikey Indexes
  • Geo-spatial Indexes and Queries
  • Text Indexes
  • Hashed Index


Index Creation

Indexes are needed to make queries faster. For example if you need to find records by a field named employeename and the field has a related index, then the query will be faster compared to without index.

Syntax

collection.createIndex(index[, options], callback)

db.createIndex(collectionname, index[, options], callback)

  • index - is the fields to be indexed.
  • options - are options, for example {sparse: true} to include only records that have indexed field.
  • callback gets two parameters -an error object (if an error occurred) and the name for the newly created index


Ensure indexes with ensureIndex()

Similar as createIndex with the difference that the index is checked for existence before adding to avoid duplicate indexes.

Syntax

collection.ensureIndex({employeename:1})


Remove indexes with dropIndex()

All indexes can be dropped at once with dropIndexes command.

Syntax

collection.dropIndexes(callback)

Get index information with indexInformation()

This can be used to fetch some useful information about collection indexes.

Syntax

collection.indexInformation(callback)

No comments:

Post a Comment