In this tutorial, I will share about better query in Mongo to increase the performance of MongoDB by using Indexes.
Write here briefly the details of what the user is going to learn in a bullet list.
Advance
In the previous tutorial I talk about CRUD operation with MongoDB. In this tutorial, I will explain how to reduce query time with MongoDB by using Indexes.
Indexes are like a key to the document. When an index is created, a "key" will be generated; and it point to the document. The reason behind the better performance is that MongoDB will scan less objects , it does not go through other document to search for that object.
let say we have a collection name user
Start the data with the following
The very straight forward way of query is as follow:
db.users.find({"name.firstName": "Johnson"});
To inspect the query performance, we will be using .explain() feature in MongoDB.
db.users.find({"name.firstName": "Johnson"}).explain('executionStats')
The result is in executionStats.totalDocsExamined. The total documents examined by MongoDB is 3 documents.
To use Indexed find, we need to use the object Id.
db.users.find({_id: ObjectId('5a8e98444c746d92c494dcd7')}).explain('executionStats');
The result is located same place as the previous one. The total documents examined is reduced to 1.
The meaning of create index is to create a documents to index link. This will increase the performance of MongoDB.
Based on the data just now, add an age document with
db.users.update({"name.firstName": "Johnson"}, {$set: {"age": 10}}).
A quick check in the total doc examined with the following mongo query:
db.users.find({age: 10}).explain('executionStats');
and the total docs examined is 3.
Adding index with the following mongo query:
db.users.createIndex({age: 1})
where age: 1 means that age is in ascending order and -1 means descending order.
Now, run a quick check in the performance on number of document examined
db.users.find({age: 10}).explain('executionStats');
The result is 1.
To check which data is index, simply run db.users.getIndexes();
The result is that _id and age is index.
Dropping index is also quite straight forward. The command is db.users.dropIndex({age:1});
MongoDB is a Document based NoSQL, where it provides a lot of powerful ways to structure data. Index is one of the way to increase performance, there is also other approach like arrays, subdocuments and geospatial feature. In the upcoming tutorial, I will cover Data Modelling, Regex and Mapping functions with MongoDB.