How to MongoDB- Indexing

Indexing supports the efficient resolution of queries. Without indexes, MongoDB must perform a collection scan, i.e. scan every document in a collection, to select those documents that match the query statement. If an appropriate index exists for a query, MongoDB can use the index to limit the number of documents it must inspect.

Indexes are special data structures that store a small portion of the collection’s data set in an easy to traverse form. The index stores the value of a specific field or set of fields, ordered by the value of the field. The ordering of the index entries supports efficient equality matches and range-based query operations. In addition, MongoDB can return sorted results by using the ordering in the index.

To create an index you need to use createIndex() method of MongoDB.

Syntax
    db.collection.createIndex(keys, options)

 

Creates indexes on collections.

ParameterTypeDescription
keysdocumentA document that contains the field and value pairs where the field is the index key and the value describes the type of index for that field. For an ascending index on a field, specify a value of 1; for descending index, specify a value of -1.

MongoDB supports several different index types including text, geospatial, and hashed indexes. See Index Types for more information.
optionsdocumentOptional. A document that contains a set of options that controls the creation of the index. See Options for details.
Example
    > db.restaurants.createIndex( { "course": 1 } );
    {  
        "createdCollectionAutomatically" : false,  
        "numIndexesBefore" : 1,  
        "numIndexesAfter" : 2,  
        "ok" : 1

 

The createIndex() method has the behaviors described here.

  • To add or change index options you must drop the index using the dropIndex() method and issue another createIndex() operation with the new options.
  • If you create an index with one set of options, and then issue the createIndex() method with the same index fields and different options without first dropping the index, createIndex() will not rebuild the existing index with the new options.
  • If you call multiple createIndex() methods with the same index specification at the same time, only the first operation will succeed, all other operations will have no effect.
  • Non-background indexing operations will block all other operations on a database.
  • MongoDB will not create an index on a collection if the index entry for an existing document exceeds the Maximum Index Key Length.

 

Indexing

MongoDB Indexing

Anwar Yakkiparamban

Anwar Yakkiparamban is the founder of Lauyou Learning. Prior to Lauyou learning, Anwar worked at ARD Engineering & Development, Qatar. He holds bachelor degree in Electronics and Communication Engineering from Govt. Engineering College Idukki.

You may also like...