MongoDB Index: Types, Properties & Limitations

Job-ready Online Courses: Click, Learn, Succeed, Start Now!

In our last MongoDB tutorial, we have discussed MongoDB Data Types. So, let’s move further with MongoDB.

In this article, we will discuss MongoDB index, advanced indexing and indexing limitation in MongoDB. Moreover, we are going to learn MongoDB properties.
So, let’s begin with MongoDB Index.

MongoDB Index: Types, Properties & Limitations

MongoDB Index: Types, Properties & Limitations

What is MongoDB Index?

For any kind of database, indexes are of great importance. In MongoDB, Indexes helps to solve queries more efficiently. Indexes are a special data structure used to locate the record in the given table very quickly without being required to traverse through every record in the table.

MongoDB uses these indexes to limit the number of documents that had to be searched in a collection. The data structure that is used by an index is a Binary Tree.

a. Default Index

In MongoDB indexing, all the collections have a default index on the _id field. If we don’t specify any value for the _id the MongoDB will create _id field with an object value. This index prevents clients from creating two documents with the same value _id field.

b. Create an Index

In MongoDB, a user can create indexes using the following syntax.

Db.collection_name.createIndex( <key and index type specification>, <options>)

This method creates an index only if the index with the same specification doesn’t exist already.
Let’s see an example that creates a single key ascending index on the name field.
We see a message that “ok”:1. That means an index has been created successfully.

> db.dataflair1.createIndex({name:1})
{
           “createdCollectionAutomatically” : false,
            “numIndexesBefore” : 1,
            “numIndexesAfter” : 2,
            “ok” : 1
}
>
MongoDB Index: Create an Index Method

MongoDB Index: Create an Index Method

Types of Index in MongoDB

MongoDB supports the following types of the index for running a query.

i. Single Field Index

MongoDB supports user-defined indexes like single field index. A single field index is used to create an index on the single field of a document. With single field index, MongoDB can traverse in ascending and descending order. That’s why the index key does not matter in this case.

ii. Compound Index

MongoDB supports a user-defined index on multiple fields as well. For this MongoDB has a compound index. There sequential order of fields for a compound index.

For example, if a compound index consists of {“name”:1,”city”:1}), then the index will sort first the name and then the city.

> db.dataflair1.find().sort({“name”:1,”city”:1})
{ “_id” : ObjectId(“Sadfeb8931cffc950c924471”), “name” : “amit”, “city” : “ujjain” }
{ “_id” : ObjectId(“Sadfeb6e31cffc950c92446f”), “name” : “ankitt”, “city” : “indore” }
{ “_id” : ObjectId(“Sadfeb7c31cffc950c924470”), “name” : “rohit”, “city” : “ujjain” }
{ “_id” : ObjectId(“Sadfeb9731cffc950c924472”), “name” : “sumit”, “city” : “devas” }
>
MongoDB Index- Compound Index

MongoDB Index- Compound Index

iii. Multikey Index

MongoDB uses the multikey indexes to index the values stored in arrays. If we index a field with an array value, MongoDB creates separate index entries for each element of the array. These indexes allow queries to select documents with the matching criteria.

MongoDB automatically determines whether to create a multikey index if the indexed field contains an array value. We do not need to specify the multikey type explicitly. Below is the example of a multikey index.

> db.dataflair1.find().sort({“name”:1,”city”:1})
{ “_id” : ObjectId(“Sadfeb6e31cffc950c92446f”), “name” : “ankitt”, “city” : “indore” }
{ “_id” : ObjectId(“Sadfeb7c31cffc950c924470”), “name” : “rohit”, “city” : “ujjain” }
{ “_id” : ObjectId(“Sadfeb8931cffc950c924471”), “name” : “amit”, “city” : “ujjain” }
{ “_id” : ObjectId(“Sadfeb9731cffc950c924472”), “name” : “sumit”, “city” : “devas” }
>
MongoDB Index - Multikey Index

MongoDB Index – Multikey Index

iv. Geospatial Index

To query geospatial data, MongoDB supports two types of indexes – 2d indexes and 2d sphere indexes. 2d indexes use planar geometry when returning results and 2dsphere indexes use spherical geometry to return results.

v. Text Index

It is another type of index that is supported by MongoDB. Text index supports searching for string content in a collection. These index types do not store language-specific stop words (e.g. “the”, “a”, “or”). Text indexes restrict the words in a collection to only store root words.

Below is the example of text index.

Here is the syntax we use for text Index

db.collection_name.createIndex({name:”text”})
> db.dataflair.createIndex({name:”text”})
{
         “createdCollectionAutomatically” : false,
            “numIndexesBefore” : 1,
            “numIndexesAfter” : 2,
            “ok” : 1
}
MongoDB Index- Text Index

MongoDB Index- Text Index

vi. Hashed Index

MongoDB supports hash-based sharding and provides hashed indexes. These indexes are the hashes of the field value.

MongoDB Index Properties

a. Unique Indexes

This property of index causes MongoDB to reject duplicate values for the indexed field. In other words, a unique property of indexes restricts it to insert the duplicate value of an indexed field. The unique indexes can be interchanged functionally with other MongoDB indexes.

Let’s see an example.

We create an index using createIndex() for the name field and set unique to be true. Then insert a document with fields “name” and “city”.

> db.dataflair.createIndex({name:1},{unique:true})
{
         “createdCollectionAutomatically” : false,
           “numIndexesBefore” : 2,
           “numIndexesAfter” : 3,
            “ok” : 1
}
> db.data-flair.insert({“name”:”ankit”,”city”:”Indore”})
WriteResult({ “nInserted” : 1 })
> db.data-flair.insert({“name”:”ankit”,”city”:”Indore”})
WriteResult({
                “nInserted” : 0,
                “writerError” : {
                           “code” : 11000,
                           “Errmsg” : “E1100 duplicate key error collection: test.dataflair index: name_1 dup key: ( : \”ankit\” }”
}
})
>
MongoDB Index- Unique Property

MongoDB Index- Unique Property

We see that when we try to insert a document again with the same field value with the unique property, an error is displayed.

So, we cannot insert duplicate values in a field with the unique property.

b. Partial Indexes

This property came in MongoDB version 3.2. Partial Indexes only index the documents that match the filter criteria. If we are creating an index with some conditions applied then it is a partial index.

Let’s create an index on the city field only with the city Indore. For this, we have to use partialFilterExpression.

> db.dataflair.createIndex({city:1},{partialFilterExpression:{name:”ankit”}})
{
         “createdCollectionAutomatically” : false,
          “numIndexesBefore” : 3,
          “numIndexesAfter” : 4,
           “ok” : 1
}
>
MongoDB Index- Partial Indexes

MongoDB Index- Partial Indexes

A message displayed as “ok”:  1 means that the partial index has been created.

c. Sparse Indexes

The sparse property ensures that the index only contains entries for documents with the indexed field. The index will skip the documents without the indexed field.

We can combine this option with the unique index option in order to reject documents with duplicate values for a field. And can ignore documents without an indexed key at the same time.
Example:

> db.dataflair.createIndex({name:1},{unique:true,sparese:true})
{
          “createdCollectionAutomatically” : false,
          “numIndexesBefore” : 2,
          “numIndexesAfter” : 3,
           “ok” : 1
}
>
MongoDB Index- Sparse Indexes

MongoDB Index- Sparse Indexes

d. TTL Indexes

TTL or “total time to live” indexes are the special indexes in MongoDB. These indexes are used to auto-delete documents from a collection after the specified time duration. The option that we use is expireAfterSecods to provide the expiration time.

This property is ideal for certain types of information like machine-generated data, logs and session information that only need to be there for a finite amount of time in a database.
Let’s create a TTL Index that deletes documents after 35 seconds.

MongoDB Index- TTL Indexes

MongoDB Index- TTL Indexes

MongoDB Indexing Limitations

Indexing in MongoDB has some limitations discussed below.

a. Range Limitations

  1. A collection cannot have indexed more than 64.
  2. The name of the index can contain only 164 characters.
  3. A compound index can have 31 fields indexed at max.

b. RAM Usage

The total size of indexes must not exceed the RAM size as the indexes are stored in the RAM. If this limit exceeds, it will cause deletion of some indexes and deteriorate the performance.

c. Query Limitations

The following factors are there for queries while indexing.

  1. Queries should not use expressions like $nin, $not, etc.
  2. Queries should not use arithmetic operators like $mod etc.
  3. A Query should not use $where clause.

d. Indexed Key Limits

MongoDB will not create an index if the value of existing index field exceeds the index key limit.

Conclusion

Now we have learned Indexing in MongoDB. We have also seen the properties of Indexing and Indexing limitation in MongoDB. We will also see how replication and sharding work in MongoDB.

We work very hard to provide you quality material
Could you take 15 seconds and share your happy experience on Google

courses

DataFlair Team

The DataFlair Team provides industry-driven content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our expert educators focus on delivering value-packed, easy-to-follow resources for tech enthusiasts and professionals.

Leave a Reply

Your email address will not be published. Required fields are marked *