MongoDB Indexing

MongoDB Indexing: Indexes provide an easy path for searching a particular document in a vast volume of data. It, in turn, increases the efficiency of the query searches, which otherwise would require the whole scanning of collection to find particular documents. MongoDB indexes limit the number of documents to be searched in the entire collection.

Indexes are a category of unique data structures, which store only a small part of the whole collection of documents. Traversing data in a small set of data is quite easy. The index contains either the value of any field or set of fields, ordered by the specified field value.

Indexes can be of just one field or it can be group of multiple fields of the collection.

Note: Indexes can make the queries easier, but too many indexes can cause overhead for the collection, which can slow down the insert, delete and update operations.

Scenario:

varemp=
 [
  {
 Empid:1,
 Empname:”Aakash”,
 Designation: “Manager”,
 Salary:60000
 },
 {
 Empid:2,
 Empname:”Ajay”,
 Designation: “Team Leader”,
 Salary:50000
 },
 {
 Empid:3,
 Empname:”Vijay”,
 Designation: “Trainee”,
 Salary:15000
 }
 ]; 

MongoDB createIndex() method

The createIndex() method is used to create an index in MongoDB.

Syntax:

db.collection_name.createIndex({fieldname/Keys:options});
Name Description Type
Keys It is a required parameter for a document containing field and value pair. The value specifies the type of index sorting. If set to 1, it sorts in ascending index and -1 sorts in descending manner. Document
Options There are some set of options in MongoDB that can control the index creation. These are optional. Document

Options Available for Indexes:

Field Type Description
Background Boolean To avoid blocking of other activities of the database, it maintains the index in the background, when set to true. By default, its value is false.
Unique Boolean This option, creates a unique set of the index, when set to true. The collection does not perform insertion operation when the index value matches an already existing value. By default, it is set to false.
Name String It is the index name. It 's length is restricted, as such that it does not exceed the Index name limit. If the user has not specified the name, then MongoDB creates it by concatenating indexed field names and the order of the sort.
Sparse Boolean If the value is set to true, then only the documents with the fields specified are used for reference. Sparse indexes use less space.
expireAfterSeconds Integer This value indicates how long MongoDB retains the document in the collection.
V Index version It specifies the version of MongoDB while the index is created. It had value 0 before version 2.0, and after version 2.0, its value is 1.
storageEngine Document It is used to specify the configuration of the storage engine.

EXAMPLE: Following command shows that how to create index on a single field:

> db.empinfo1.createIndex({Empid:1})
  1. Here, the createIndex method creates an index with the empid field of the document.
  2. The parameter 1 sorts the document in ascending order and -1 in descending order based on the field specified within the parameter.

Output:

{
  "createdCollectionAutomatically" : false,
  "numIndexesBefore" : 1,
  "numIndexesAfter" : 2,
  "ok" : 1
 } 

After successful execution of this operation numIndexesBefore & numIndexesAfter represent the Field value before & after the index is created. So here, the values are 1 & 2, respectively. The ok:1 specifies the successful execution of the operation.

Example: How to create index using multiple field values?

 > db.empinfo1.createIndex({Empid:1, Empname:1})

Output:

{
 ;;;;;;; "createdCollectionAutomatically" : false,
 ;;;;;;; "numIndexesBefore" : 2,
 ;;;;;;; "numIndexesAfter" : 3,
 ;;;;;;; "ok" : 1
 } 

In the above example, the index is created with two fields Empid & Empname.

MongoDB getIndexes()

 The following command will execute the existing index in your defined collection:

> db.empinfo1.getIndexes();

Output:

[
  {
  "v" : 1,
  "key" : {
  "_id" : 1
  },
  "name" : "_id_",
  "ns" : "empdb.empinfo1" 
  },
  {
  "v" : 1,
  "key" : {
  "Empid" : 1
  },
  "name" : "Empid_1",
  "ns" : "empdb.empinfo1" 
  },
  {
  "v" : 1,
  "key" : {
  "Empid" : 1,
  "Empname" : 1
  }, 
  "name" : "Empid_1_Empname_1",
  "ns" : "empdb.empinfo1"
  }
 ]  

MongoDB Drop Indexes

It accepts the field which needs to be removed from the index. The code given below drops the created index.

> db.empinfo1.dropIndex({Empid:1})

Output:

{ "nIndexesWas" : 3, "ok" : 1 }

Here, the “ok”:1 represents the successful execution of the operation.

To remove all the indexes:

To drop all the indexes of the collection you can use the following command.

> db.empinfo1.dropIndexes();

Output:

{
  "nIndexesWas" : 2,
  "msg" : "non-_id indexes dropped for collection",
  "ok" : 1
 } 

After the successful execution of this command you can find that all the indexes have been removed except for the _id.