You probably already know how flexible and versatile MongoDB is, and it is gaining popularity day by day. MongoDB has a lot of features to offer. We've already covered all the basic things you need to know about creating and manipulating MongoDB databases. Now let's learn about Indexes in MongoDB, what they are, how they work, and the types of indexes MongoDB has.
Indexes in MongoDB
Indexes in MongoDB are the data structures that help us find the data (Documents in the case of MongoDB) in the database. For example, in hospitals, there are vast amounts of records of all their patients. If we need a record of a certain patient, we will have to go through each and every record in order to find the one that we need. To tackle this issue we use indexes, where the patients are labeled according to their initials or their date of entry.
Similarly, in the case of MongoDB, we would need to go through the entire collection in order to find the document we are searching for, which can be time-consuming and very inefficient. Indexes come in handy here to improve the performance of search operations.
Types of indexes
There are multiple types of indexes that MongoDB provides. Before discussing the types of indexes, imagine that there is a database of multiple students with their names, ages, and the scores they received.
{
"_id" : ObjectId("644101ea9c7c9b396ddea238"),
"name" : "Alice",
"age" : 20,
"score" : 85
}
{
"_id" : ObjectId("644101ea9c7c9b396ddea239"),
"name" : "Bob",
"age" : 22,
"score" : 92
}
{
"_id" : ObjectId("644101ea9c7c9b396ddea23a"),
"name" : "Charlie",
"age" : 19,
"score" : 78
}
{
"_id" : ObjectId("644101ea9c7c9b396ddea23b"),
"name" : "David",
"age" : 21,
"score" : 90
}Single field index
In a collection of MongoDB, there are multiple documents, and the documents there contain fields and values. All the collections already have indexed values by default. Indexing created by users for a single field within the collection to support the users' queries is called the single field index. Such indexes are the simplest of all and are mostly used in cases where fields need to be filtered or sorted. There are two default values, 1 and -1. When the value of the index is 1, it signifies the indexes in ascending order, whereas -1 signifies the values in descending order.
Suppose there is a collection students, we need to create indexes for the students for the field score. Let's create a single field index for the score:
db.students.createIndex({ score: 1 })Compound field index
Now that we know how to create indexing for a single field index, let's learn about the compound field index. It's the indexing created for more than one field in a document.
Here's an example. In the collection mentioned before, there are multiple documents and in the documents, there are multiple fields. Let's create indexing for the fields of name and age.
db.students.createIndex({ name: 1, age: -1 })In this example, we've created an index for multiple fields, names, and ages. The indexes are created in ascending and descending order respectively.
Multi-key index
We know that MongoDB is schema-less. Therefore, there may be different kinds of fields in the documents. For example strings, integers, arrays, etc. For the single field and compound index the values in the fields were either integer or string. There was only one value in the field, hence creating an index for them was simple. But what do we do when the values contain arrays? This is when the multi-key index comes in handy.
If we were to create single or compound field indexes for the field which contains an array, only the key would be counted as one index, not the values it contains. Therefore to index the values inside the field, which contains an array, the multi-key index is used.
Let's review a collection in MongoDB that contains an array to better understand the concept of the multi-key index.
{
"_id" : ObjectId("6448c2b885fe9a30659e615c"),
"name" : "Harry",
"age" : 18,
"hobbies" : [
"football",
"cooking",
"photography"
]
}
{
"_id" : ObjectId("6448c2b885fe9a30659e615d"),
"name" : "Tommy",
"age" : 17,
"hobbies" : [
"travelling",
"singing",
"dancing"
]
}In this example, single and compound field indexes can be created for all the fields, name and age, but things get complicated when it comes to hobbies. Yes, single and compound field indexes can be created for hobbies but one index is assigned to the field as a whole, not the values it contains.
Since there are multiple values in the field, to index all the values it contains we will need to use a multi-key index:
db.students.createIndex({ hobbies: 1})Unique index
There may be instances where unique values need to be inserted to maintain data integrity and consistency. Specifically, in the cases where the data won't be repeated. In these cases, the unique index is used. Let us take a look at an example.
Suppose there is a list of students in the school's record. There are many students in the school and they might have similar names. So to prevent the confusion of data between any two students with similar names, we add a field that creates uniqueness in each document of the student. Let the unique field be phonNumber.
db.students.createIndex({ phoneNumber: 1 }, { unique: true })Now that a unique field has been created, the phone numbers that are to be inserted in the document must themselves be unique.
db.Students.insertMany([
{
name: "Bob",
age: 22,
phoneNumber: "987-654-3210"
},
{
name: "Charlie",
age: 25,
phoneNumber: "555-555-5555"
}
])
If the unique phone numbers are inserted in the collection, it is acknowledged to be true.
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("6448d00d85fe9a30659e6162"),
ObjectId("6448d00d85fe9a30659e6163")
]
}But if the phone numbers are repeated,
db.Students.insertOne({
name: "Bob",
age: 22,
phoneNumber: "987-654-3210"
})The error is shown:
WriteError({
"index" : 0,
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: test.
Students index: phoneNumber_1 dup key: { phoneNumber: \"987-654-3210\" }"Several types of indexes have been described here. But the topic of indexing is vast, there are more types of indexing that you can search for. The other types include text index, hash index, and geospatial index.
Listing indexes
Now that we have created several types of indexes, we will need to list them. There are several benefits of listing the indexes, it helps maintain the data integrity and consistency In the collection. As there are many documents in a collection, creating indexes consumes space, so routinely listing and checking for the more important indexes may be quite helpful in the data processing. Let's see how we can list the already created index from the database above of students.
db.students.getIndexes()The following command lists the indexes from the collection.
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_"
},
{
"v" : 2,
"key" : {
"score" : 1
},
"name" : "score_1"
},
{
"v" : 2,
"key" : {
"hobbies" : 1
},
"name" : "hobbies_1"
}
]In this example, "_id" is an automatically created index that is used to uniquely identify each and every document created in the collection. The other indexes, score and hobbies, are the indexes we created ourselves in the collection. score_1 and hobbies_1 are the names given to the indexes.
Removing the indexes
Since the indexes use some of the storage in the collection, it's really important to manage them. Sometimes knowing how to remove the indexes comes in handy. Suppose, we don't need the index of hobbies in the collection of students anymore. Let's remove the index hobbies from the collection.
The indexes have already been listed in the example above.
db.students.dropIndex("hobbies_1")The following command removes the index created for hobbies.
Let's see if the index has been dropped, by listing the indexes.
db.students.getIndexes()
[
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_"
},
{
"v" : 2,
"key" : {
"score" : 1
},
"name" : "score_1"
}
]As you can see, the index for hobbies was removed.
Conclusion
Let's go over the main points covered in this topic once again.
Indexes in MongoDB are the data structures that help us find the documents in the case of MongoDB in the database.
There are many types of indexes in MongoDB. Single field index, compound field index, multi-key index, and unique index are some of them.
There are also other indexes like text index, hash index, and geospatial index.
Single-field indexes are created for a single field in the collection.
Compound field indexes are created for more than one field in the collection.
Multi-key indexes are in a field with more than one value. For example, a field containing arrays.
A unique index uniquely inserts each and every value inserted in a field and doesn't allow reoccurring values.
Listing and removing the indexes is necessary to manage the documents in the collections.