MongoDB – Create Index:

Collections with millions of documents with no indexes will result in poor performance of filtering queries based on query criteria. Using indexes will ensure the efficient way of executing the Queries in a database.

In MongoDB, indexes are like same as in RDBMS. If we don‘t have index on required field, it turns into entire collection scan which will read all documents in a collection.

Indexes are special data sets which can store the value of specific field or set of fields.

When we create Index?

Even too many indexes will result poor performance of queries. Yes, even though the collection has millions of records, if you have very frequent DML operations on documents, then it will be overhead for collection to maintain the datasets of all indexes created. So, before creating the index we should analyse where is it required and all.

Syntax:

Let‘s create the index on field “firstname” in collection “Students”.

Example:

We can also create Index on multiple fields in a collection.

Example:

You can verify the indexes created in a collection.

Syntax:

Example: