Indexes in MongoDB are just like indexes in the book.
Instead of going page by page in a Book one can get to any Topic by searching on the index.
In MongoDB, these indexes are made of btree. These btree orders the Documents and guide to the required one with a far lesser read operation.
But all this speed doesn’t come for free. Writing operations are inversely proportional to the number of indexes in a DB.
More the indexes more the need to balance them on every write.
Types of indexes:-
- Single Field Index
As the name suggests these are comprised of a single field. This is the simplest form of an index.
db.your_collection.createIndex(
{
field_to_be_indexed: 1
}
)
NOTE:- 1 at the end of the command is to index in ascending order.
- Compound Index
The compound index is those index containing more than one fields. In this type of index, order plays an important role as Mongo Db will create Index in Orderly fashion.
db.your_collection.createIndex(
{
first_field_to_be_indexed: 1,
second_field_to_be_indexed: 1
}
)
- Multikey Index
It is an advanced version of the compound index as it can contain array values of subfields in a document. That too multiple of them
db.your_collection.createIndex(
{ first_field_to_be_indexed:
[
field1: 1,
field2: 1
]
}
)
Multikey indexes are most Complex and needed to execute with utmost precaution as this index can lead to a large index file which can harm the operation of writing anything.
There is more type of indexes that we will talk about in the next part.