A database is a data structure that stores or collects structured data. Mongo DB is a NO SQL database that stores information in key-value pairs. Below are terminologies we need to know before going into indexing in Mongo DB.
Collections: Collections are a cluster of Mongo DB documents that reside in a single database. The concept of relational schema is not implemented in the collections. The documents of Mongo DB that have collections consist of various fields.
Document: A document is a collection key-value pair that consists of a dynamic schema. Because it’s dynamic it changes the way you add data. In Mongo DB it’s needless to characterize a schema ahead of time.
Now let’s discuss indexing. Indexing is a required option that brings efficiency to the execution of statements.
The idea of indexing is important for Mongo DB or any other database. The indexed databases make the query performance more systematic. Suppose you have a collection of hundreds of documents withoux2t indexing, then the query will keep on going through a loop of specific documents indefinitely, hence taking more time. But if your document consists of indexes, Mongo DB will go with a definite number of documents that will be searched in the collection.
createIndex()
methodcreate index() is a method used to create an Index.
Syntax:
1
2
3
Db.name_of_collection.createIndex()({
Key: A
})
The key in the syntax above is the name of a field that you want to make the index. The range of the values of the index will be -1 to 1 to make it in ascending or descending order.
Example:
1
2
3
Db.col.createIndex({
title: 1
})
We created an index on the title field, which means when someone searches a document based on the title, the search will be automatically faster.
Below are the optional parameters that can be used in create index method:
Background: By using this you can make the index in the background so that other database activities do not stop. The data type of this parameter is Boolean.
Sparse: If the value is true, the index mentions documents with certain fields.
Name: It is the name of the index. If you don’t specify the name of the index, Mongo DB automatically generates it by concatenating the index fields and arranging it.
Expireafterseconds: It mentions the total time limit to control for how much time a NoSQL database retains a document.
DropIndex()
methodOne can drop a specific index using the DropIndex() method of Mongo DB.
Syntax:
1
2
3
Db.name_of_collection.dropIndex({
KEY: A
})
The name of the file is the “key” on which you want to delete the existing index. Instead of the above syntax, you can directly specify the name of the document like the below syntax.
Syntax:
1
dropIndex(“index_name”)
Code:
1
2
3
4
5
Db.mycollec.dropIndexes({
“
title”: 1,
jobfunction: -1
})
The method tells us the description of each of the indexes in the entire collection.
Syntax:
1
Db.name_of_collection.getIndexes()
Code:
1
Db.mycollec.getIndexes()
The above code returns the following.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[
{
"v": 2,
"key": {
"id": 1
},
"name": "_id_"
},
{
"v": 2,
"key": {
"status": 1
},
"name": "status_1"
}
]
The information that is returned includes the options and keys to create the index.
Now let’s look at viewing a user document depending on its tags. To do that one needs to create an index on your array within your collection. For making an index based array one needs to create different index entries for separate fields.
Below is the implementation for the same:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13
{ "location": { "city": "Alberta", "Ontario" "country": "Canada" }, "tags": [ "contentwriter" "developer" "programmer" ], "name": "Adam" }
FIND COMMAND:
When the index is created we can search on the tags field of the collection of indexes like below:
Code:
1
2
3
4
Db.users.find({
tags: “programmer”
})
.pretty()
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
{ "_id": ObjectId(" 5dd7c834f1dd472e7102fdf"), "location": { "city": "Alberta", "Ontario" "country": "Canada" }, "tags": [ "contentwriter" "developer" "programmer" ], "name": "Adam" }
EXPLAIN COMMAND:
To know if the user has done proper indexing, we can use the explain command to check for it.
Code:
1
2
3
4
Db.users.find({
tags: “programmer”
})
.explain()
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
{ "queryPlanner": { "plannerVersion": 1, "namespace": "db.users", "indexFilterSet": false, "parsedQuery": { "tags": { "$eq": "programmer” } }, "queryHash": "9B3D61B7", "planCacheKey": "04D9997C", "winningPlan": { "stage": "FETCH", "inputStage": { "stage": "IXSCAN", "keyPattern": { "tags": 1 }, "indexName": "tags_1", "isMultiKey": false, "multiKeyPaths": { "tags": [] }, "isUnique": false, "isSparse": false, "isPartial": false, "indexVersion": 2, "direction": "forward", "indexBounds": { "tags": ["[\" programmer \", \" programmer \"]"] } } }, "rejectedPlans": [] }, "serverInfo": { "host": "Krishna", "port": 27017, "version": "4.2.1", "gitVersion": "edf6F45851cb0c9ee15548f0f847df141764a317e" }, "ok": 1 }
Let’s suppose you want to view documents on the basis of the country and city fields. For this, we need to generate an index of each of the sub-document fields. Below is the code for generating an index on sub-documents.
Code:
1
2
3
4
5
db.users.createIndex({
“
location.country”: 1,
“location.city”: 1
})
When the indexes are created then one can use the find function to search for a specific country or city.
Code:
1
2
3
4
db.users.find({
“
location.city”: “Ontario”
})
Usage of RAM: The indexes created in Mongo DB get stored in the RAM, so you need to ensure that the index does not go beyond the size of the RAM.
Query Limitations: Indexing is not suited for queries that make use of the following:
$where clause
$mod or any other arithmetic operators.
Regular expressions
For one specific collection there can be just 64 indexes.
The index field quantity in a compound index won’t exceed more than 32 fields.