What is Advanced Indexing in MongoDB | Its Types | Limitations

If You are interested to learn about the Atomic Operations

What is Indexed in MongoDB?

MongoDB employs indexing to speed up the response time to queries. The MongoDB must scan every document in the collection if there is no indexing and only get documents that match the query.

Create an Index :

Along with the default index, we can create indexes on our own using the createIndex() method. This method creates one or more indexes on the specified collections.

Syntax 

db.Collection.name.createIndex(

    keys : {Field_name:1/-1},

    options : <document>,

    commitQuorum : <string or integer>

)

Example:

In the following examples, we are working with:

Database: gfg

Collection: students

Document: Four documents that contains the details of the students

db.students.createIndex({studentsId:1})

In the below image, first, we find the collection details. So, here collection name is students and in which we want to create an index over “studentId” column. 

Note: MongoDB is case-sensitive. So, studentId and studentid are treated differently.

On executing our query we got the message as “ok” meaning that an index is created and also “numIndexesAfter”: 2″ one index is already available(default index) and hence the count is increased by 2.

Types of Index in MongoDB

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

i. Single Field Index

Single field indexes and other user-defined indexes are supported by MongoDB. To establish an index on a single field in a document, use a single field index. MongoDB may traverse in ascending and descending order with a single field index. Because of this, the index key is irrelevant in this situation.

ii. Compound Index

A user-defined index on multiple fields is also supported by MongoDB. MongoDB has a compound index for this. For a compound index, the fields are arranged sequentially.

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” }
>

iii. Multikey Index

The values stored in arrays are indexed by MongoDB using multikey indexes. When an array value is used to index a field, MongoDB distinct index entries are created for each element of the array. Queries can use these indexes to choose documents that meet the specified criteria.

If the indexed field has an array value, MongoDB decides on its own whether to generate a multikey index. The multikey type does not need to be stated explicitly. Here is an illustration 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” }
>

iv. Geospatial Index

MongoDB supports the 2d index and the 2d sphere index for geographical data queries. When providing results, 2d indexes employ planar geometry whereas 2dsphere indexes use spherical geometry.

v. Text Index

It is an additional type of index that MongoDB supports. Searching for string content in a collection is supported by text index. The, a, and or are examples of language-specific stop words that are not stored in these index types. Text indices limit a collection of words to only storing root words.

Below is the example of text index.

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

vi. Hashed Index

Hash-based sharding is supported by MongoDB, which also offers hashed indexes. The field value’s hashes are represented by these indexes.

MongoDB Index Properties

a. Unique Indexes

MongoDB rejects duplicate values for the indexed field as a result of this index attribute. In other words, an index’s ability to be unique prevents it from allowing the insertion of a duplicate value for an indexed field. The functional interchangeability of the unique indexes 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\” }”
}
})
>

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 first appeared in MongoDB 3.2. Only the documents that meet the filter criteria are included in partial indexes. A partial index is one that has conditions applied as it is being created.

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
}
>

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

c. Sparse Indexes

The index will only have entries for documents that have the indexed field thanks to the sparse attribute. The papers without the indexed field will not be included in the index.

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- Sp

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 expire After Seconds 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 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.

What is Advanced Indexing in MongoDB | Its Types | Limitations
Show Buttons
Hide Buttons