Indexing in MongoDB
MongoDB is leading NoSQL database written in C++. It is high scalable and provides high performance and availability. It works on the concept of collections and documents. Collection in MongoDB is group of related documents that are bound together. The collection does not follow any schema which is one of the remarkable feature of MongoDB.
Indexing in MongoDB :
MongoDB uses indexing in order to make the query processing more efficient. If there is no indexing, then the MongoDB must scan every document in the collection and retrieve only those documents that match the query. Indexes are special data structures that stores some information related to the documents such that it becomes easy for MongoDB to find the right data file. The indexes are order by the value of the field specified in the index.
Creating an Index :
MongoDB provides a method called createIndex() that allows user to create an index.
Syntax –
db.COLLECTION_NAME.createIndex({KEY:1})
The key determines the field on the basis of which you want to create an index and 1 (or -1) determines the order in which these indexes will be arranged(ascending or descending).
Example –
db.mycol.createIndex({“age”:1})
{
“createdCollectionAutomatically” : false,
“numIndexesBefore” : 1,
“numIndexesAfter” : 2,
“ok” : 1
}
The createIndex() method also has a number of optional parameters.
These include:
- background (Boolean)
- unique (Boolean)
- name (string)
- sparse (Boolean)
- expireAfterSeconds (integer)
- hidden (Boolean)
- storageEngine (Document)
Drop an index:
In order to drop an index, MongoDB provides the dropIndex() method.
Syntax –
db.NAME_OF_COLLECTION.dropIndex({KEY:1})
The dropIndex() methods can only delete one index at a time. In order to delete (or drop) multiple indexes from the collection, MongoDB provides the dropIndexes() method that takes multiple indexes as its parameters.
Syntax –
db.NAME_OF_COLLECTION.dropIndexes({KEY1:1, KEY2: 1})
The dropIndex() methods can only delete one index at a time. In order to delete (or drop) multiple indexes from the collection, MongoDB provides the dropIndexes() method that takes multiple indexes as its parameters.
Get description of all indexes :
The getIndexes() method in MongoDB gives a description of all the indexes that exists in the given collection.
Syntax –
db.NAME_OF_COLLECTION.getIndexes()
It will retrieve all the description of the indexes created within the collection.
Contact Us