Indexes support the efficient execution of queries in MongoDB. Without indexes, MongoDB must perform a collection scan, i.e, scan every document in a collection, to select these documents to match the query statement. We require indexing for a faster query. With Indexing, we can arrange data in a sorted way. MongoDB creates a unique index on the _id field during the creation of a collection. B-Tree is the Data structure behind indexing.
There are 6 types of Indexes: Single Field; Compound Index; Multikey Index; Geospatial Index; Text Index; Hashed Index.
To create an index in MongoDB, the syntax to use is:
db.collection.createindex({fieldname:direct})
Direction-direct may be ascending or descending for direction value 1 is for ascending and -1 for descending.
To get an existing index on a collection in MongoDB, the syntax to use is:
db.collection.getIndexes()
To remove a specified index on a collection, the syntax to use is:
db.collection.dropIndex(indexName)
Indexname: parameter as index name or index specified document
To remove all indexes on a collection, the syntax to use is:
db.collection.dropIndexes()