MongoDb Indexing

Indexing is the most important part of every database. It is basically used to fast retrieve data from the database.

Why indexing is most important?

Indexing is mainly used to filter data in a fast manner from the database that is the reason it is most important.

Example:- Suppose you have a collection of thousands of documents and you want to filter the document based on any condition, if you have not created indexing on the field(key) then it will check the condition in every document, so it will be impacted in the performance of the query. If we create indexing then MongoDB would use these indexes to limit the number of documents to search in the collection.

Note:- in MongoDB, every document has _id (ObjectID), which is automatically created when you create a Document and it has a 12 digit number with unique value.

divide the 12 digit Object ID

4-byte value representing the seconds since the Unix epoch (which will not run out of seconds until the year 2106)
3-byte machine identifier (usually derived from the MAC address),
2-byte process id.
3-byte counter, starting with a random value.

How to create an index?

In MongoDB, Creating a index through createIndex() method

Syntax:-


 db.collectionName.createIndex({key:1})

Where a key is a document key.

Note:- You can create multiple indexing in a document.

Example:-


 db.employees.createIndex({department:1})

Output:-

{
“createdCollectionAutomatically” : false,
“numIndexesBefore” : 1,
“numIndexesAfter” : 2,
“ok” : 1
}

Note:- Ok represent 1, it means index created successfully.

How to check the all indexes from the collection?


db.collectionName.getIndexes()

Example:-


db.employees.getIndexes()

Output:-

[
{
“v” : 2,
“key” : {
“_id” : 1
},
“name” : “_id_”,
“ns” : “employee_management.employees”
},
{
“v” : 2,
“key” : {
“department” : 1
},
“name” : “department_1”,
“ns” : “employee_management.employees”
}
]

How to drop the indexes from the collection?


db.collectionName.dropIndex({key:1})

Example:-


db.employees.dropIndex({department:1})

Output:-

{ “nIndexesWas” : 2, “ok” : 1 }