/    /  MongoDB – Create Index

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:

db.collection.createIndex(<key and index type specification>,<options>)

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

Example:

db.students.createIndex({firstname:1}) --> where 1 indicates the ascending sort order.
testset:PRIMARY>db.students.find()
{ "_id" : ObjectId("59245acd5273c93ad95b109b"), "firstname" : "Maria", "city" : "Banglore" }
{ "_id" : ObjectId("59246d4b5273c93ad95b109c"), "firstname" : "sneha", "city" : "Delhi" }
{ "_id" : ObjectId("59246d7b5273c93ad95b109d"), "firstname" : "jay", "city" : "toronto" }

testset:PRIMARY>db.students.createIndex({firstname:1})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}

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

Example:

db.students.createIndex({firstname:1, city:1})
testset:PRIMARY>db.students.createIndex({firstname:1,city:1})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 2,
        "numIndexesAfter" : 3,
        "ok" : 1
}

You can verify the indexes created in a collection.

Syntax:

db.collection.getIndexes()

Example:

testset:PRIMARY>db.students.getIndexes();
[
        {
                "v" : 1,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "test.students"
        },
        {
                "v" : 1,
                "key" : {
                        "firstname" : 1
                },
                "name" : "firstname_1",
                "ns" : "test.students"
        },
        {
                "v" : 1,
                "key" : {
                        "firstname" : 1,
                        "city" : 1
                },
                "name" : "firstname_1_city_1",
                "ns" : "test.students"
        }
]