Before reading this article, I highly recommend reading the following previous parts of the series:
Introduction
Indexes support the efficient resolution of queries. Indexes execute queries in an efficient way. Without indexing, MongoDB does a collection scan. In a collection scan MongoDB scans each document individually to select those documents that match the selection criteria. This approach takes much time and resources. So MongoDB provides indexes that can provide a reliable and efficient way of scanning documents. If an appropriate index exists for a query then MongoDB can use this index to limit the number of documents it must scan.
Indexes are special data structures that store a small portion of the data set in an easy to traverse form. The index can store the value of a specific field or a set of fields, ordered by the value of the field that is specified in the index.
Types of Index
MongoDB supports several types of indexes. We can create an index on a single field, multiple fields, an index for an embedded field or an index for embedded documents. We should create an index for fields frequently used in queries, such that we can ensure that MongoDB scans the smallest possible number of documents. The createIndex() method creates indexes.
MongoDB has the following types of indexes.
- Default Index
- Single Field Index
- Compound Index
- MultiKey Index
- Text Index
- Geospatial Index
- Hashed Index
Now to briefly describe each type of index.
Default _ID
Each MongoDB collection contains a builtin index on the _id field of the collection. This is a default index used by MongoDB. The index of the _id field contains the Unique property. In other words, we can’t insert a duplicate value into the _id field. If we don’t specify the value for the _id field then MongoDb inserts a unique value into the _id field automatically. The index of the _id field stores the data in ascending order.
Example
db.post.find({},{_id:1,Likes:1}).pretty()
- { "_id" : ObjectId("55c545e1acae58b1a7d7dff1"), "Likes" : 5 }
- { "_id" : ObjectId("55c54617acae58b1a7d7dff2"), "Likes" : 4 }
- { "_id" : ObjectId("55c54665acae58b1a7d7dff3"), "Likes" : 4 }
- { "_id" : ObjectId("55c546a6acae58b1a7d7dff4"), "Likes" : 5 }
- { "_id" : ObjectId("55c546d9acae58b1a7d7dff5"), "Likes" : 3 }
- { "_id" : ObjectId("55c54711acae58b1a7d7dff6"), "Likes" : 6 }
In the preceding example we retrieve _id, like a field from the “post” collection. The _id in the preceding output is in ascending order.
Single Field IndexIn MongoDB we can create an index for a single field or multiple fields. To create an index on a single field, pass the name of that field with the sorting order option.
Syntaxdb.Collection_Name.createIndex({field:sorting_order})
Sorting_Order1 for sort in ascending order and -1 for sort in descending order.
Exampledb.post.createIndex({Likes:1})
Output
- {
- "createdCollectionAutomatically": false,
- "numIndexesBefore": 1,
- "numIndexesAfter": 2,
- "ok": 1
- }
In the preceding example we create an index on the “Likes” field and specify 1 for the sorting order. In other words, the index orders the items in ascending order. We can see the createIndex() method return 4 parameters in acknowledge. The first parameter is “createdCollectionAutomatically” that specifies that this index is user-defined or created by the collection automatically. The second parameter is “numIndexesBefore” that specifies the number of indexes before the execution of the current command. The third parameter is “numIndexesAfter” that defines the number of indexes after the execution of the current command. The fourth parameter is “ok” that indicates the creation of an index, 1 for success and 0 for failure.
Index on Embedded FieldIn the previous example we create an index for the top level field such that we can create an index for the field of the embedded document. Use “dot notation” to create an index on the embedded field.
Example
- {
- "_id": ObjectId("55c545e1acae58b1a7d7dff1"),
- "PostBY": "Pankaj choudhary",
- "Time": ISODate("2015-08-07T23:57:21.041Z"),
- "Title": "Introduction of MongoDB",
- "Tags": [
- "NoSQL",
- "MongoDB",
- "Database"],
- "Likes": 5,
- "Comment": {
- "CommentBy": "Rahul",
- "Text": "Nice Article"
- }
-
- }
Now we create an index on the “CommentBy” field of the embedded document using the following specification.
db.post.createIndex({"Comment.CommentBy":1})
Index on Embedded DocumentIn the previous example we create an index for the embedded field. Now we create an index for the embedded document.
For example, the post collection contains the “Comment” field that is an embedded document.
Exampledb.post.createIndex({"Comment":1})
Compound IndexesIn MongoDB we can create an index for multiple fields of a collection. MongoDB supports 31 fields in a single compound index.
The following is an example:
- {
- "_id": ObjectId("55c545e1acae58b1a7d7dff1"),
- "PostBY": "Pankaj choudhary",
- "Time": ISODate("2015-08-07T23:57:21.041Z"),
- "Title": "Introduction of MongoDB",
- "Tags": [
- "NoSQL",
- "MongoDB",
- "Database"],
- "Likes": 5,
- "Comment": {
- "CommentBy": "Rahul",
- "Text": "Nice Article"
- }
-
- }
Now we create a compound index of two fields with the following sorting order.
db.post.createIndex({"Comment":1,Title:-1})
The preceding query indexes the sort first by the “Comment” field in ascending order then by the “Title” field in descending order.
PrefixesAn Index prefix refers to the beginning subsets of indexed fields. Let us see an example:
db.post.createIndex({Comment:1,Title:-1,PostBy:1})
The preceding index has the following index prefixes:
- { Comment:1}
- {Comment:1,Title:-1}
MongoDB uses the preceding index for queries containing the following fields.
- Comment field
- Comment and Title field
- Comment and Title and PostBY field
MongoDB never uses the preceding index for queries that contain the following fields.
- Title field
- PostBY field
- Title and PostBY field
MongoDB can use the preceding index for queries that contain “Comment” and “PostBY” fields because the “Comment” field corresponds to a prefix. But this index would not be as efficient as a separate index for the “Comment” and “PostBY” fields.
MultiKey Indexes
If we create an index on a field that holds the array value then MongoDB creates an index key for each element in the array. Multikey indexes support efficient queries against array fields. Multikey indexes can be created on an array field that contains either scalar values (in other words string or Integer) or nested documents. MongoDB automatically creates a multikey index if an indexed field is an array type. We don’t need to specify the multikey type.
Let us see an example:
- {
- "_id": ObjectId("55c54711acae58b1a7d7dff6"),
- "PostBY": "Pankaj choudhary",
- "Time": ISODate("2015-08-08T00:02:25.968Z"),
- "Title": "MongoDB Day3",
- "Tags": [
- "NoSQL",
- "MongoDB",
- "Database"],
- "Likes": 6,
- "Comment": [{
- "CommentBy": "Neeraj",
- "Text": " Nice One"
- }, {
- "CommentBy": "Rahul",
- "Text": "Thanks to Share"
- }]
- }
In the preceding document we have two fields that are array types. The first one is “Tags” that contain scalar values and the second is “Comment” that contains nested documents. Now we create an index for both fields.
Index for “Tags” field.
db.post.createIndex({"Tags":-1})
Index for “Comment” field.
db.post.createIndex({"Comment":1})
Compound Multikey IndexesIn the previous example we create two indexes, one for the “Tags” field and another for the “Comment” field. But we can’t create a compound index if more than one field is the “Array” type.
Let us try to create a compound index for the “Tags” and “ Comment” fields.
db.post.createIndex({"Comment":-1,"Tags":1 })
Output
- {
- "createdCollectionAutomatically": false,
- "numIndexesBefore": 10,
- "errmsg": "exception: cannot index parallel arrays [Tags] [Comment]",
- "code": 10088,
- "ok": 0
- }
MongoDB throws an error if we execute the preceding query because MongoDB doesn’t allow creation of a compound index for multiple “Array” fields.
But we can create a compound index if at most one field is the “Array” type.
db.post.createIndex({"Comment":-1,"Title":1 })
Text IndexesMongoDB provides the feature “Text Index” to search the string contents in the documents of a collection. The Text Index can contain any field that has a string or array of strings. A collection can have at most one text index. But we can specify multiple fields for the text index.
To create a Text Index field set the value of the “comments” parameter to “text” in the createIndex() method.
Syntaxdb.Collection_Name.createIndex({comments:”text”})
Example1db.post.createIndex({"Title":1 },{comments:"text"})
Example2db.post.createIndex({"Title":1 ,PostBY:1},{comments:"text"})
Wildcard Text IndexesWe know that a MongoDB database consists of unstructured data, so sometimes it is difficult to predict which fields contain text type data. MongoDB provides the wildcard specifier ($**) to allow for a text search on all fields with string content. Using a wildcard index MongoDB indexes all the fields containing string or text type data.
Let us see an example:db.post.createIndex( { "$**": "text" } )
The preceding example creates a text index using wildcard specifier.
We can create a wildcard text index in compound index. Let us see an example.
db.post.createIndex({"Title":1,"$**":"text"})
In the preceding example we create a compound index. This compound index contains a “Title” field and wildcard text index.
Geospatial IndexesA Geospatial index is mainly used to store the location data or geospatial information. Before storing any data we must be decide the type of surface. MongoDB supports two types of surfaces.
- Spherical
Calculates the geometry over a spherical surface (such as Earth) and stores location data on a spherical surface using 2dsphare.
- Flat
Calculates distance over an Euclidean and store location as legacy coordinate pairs using a 2d index.
Hashed Index
In Hashed indexed entries are maintained with hashes of the values of the indexed field. The Hashing function collapses embedded documents and computes the hash for the entire value. A Hashed index supports equality queries but doesn’t support range queries and multi-key index. We can’t create a compound index for a Hashed index. However we can create a non-hashed index (such as a single field or a compound index) and hashed index on the same field.
Syntax
db.Collection_Name.createIndex({Field:”hashed”})
Let us see an example:
db.post.createIndex({"Title":"hashed"})
In the preceding query we create a hashed index on the “Title” field.
Index Properties
Indexes in MongoDB supports these three properties for indexes.
- Unique Index
- TTL Index
- Sparse Index
Unique Index
Unique index properties are used to restrict all the documents with a duplicate value for the indexed field or that already exist. To create a unique index, set the value of the “Unique” parameter to “true” in the createIndex method. By default the value of unique is false.
Syntax
db.Collection_Name.createIndex({fieldname:sorting_order},{unique:true})
Example
Consider the following “Demo” collection. The Id field of the “Demo” collection has the following values.
db.My_Collection.find({},{_id:0})
- { "Id" : "1" }
- { "Id" : "2" }
- { "Id" : "3" }
Now we create a Unique index on the “Id” field .
db.Demo.createIndex({"Id":1},{unique:true})
Now we try to insert a duplicate value into the “Id” field.
db.Demo.insert({Id:"1"})
Output
- WriteResult
- ({
- "nInserted" : 0,
- "writeError" :
- {
- "code" : 11000,
- "errmsg" : "E11000 duplicate key error index: Temp.Demo.$Id_1 dup key: { : \"1\ " }"
- }
- })
This output shows that if we try to insert a duplicate value into the “Unique” field then MongoDB will throw an error.
TTL IndexesTTL indexes are special types of indexes that MongoDB uses to remove documents automatically from a collection after a certain time period. This approach is very useful for machine generating data, logs, session information or storing the information for a temporary time period. To create a TTL index, use the expireAfterSeconds option with the createIndex method. In the expireAfterSeconds option we provide the time period in seconds. The TTL index does not guarantee that expired data will be deleted immediately upon expiration. There may be a delay between the time a document expires and the time that MongoDB removes the document from the database.
Syntaxdb.Collection_Name.createIndex({fieldname:sorting_order},{ expireAfterSeconds:time})
ExampleThe Demo collection contains the following documents.
- {
- "Id": 1,
- "Name": "Pankaj"
- } {
- "Id": 2,
- "Name": "Rahul"
- } {
- "Id": 3,
- "Name": "Sandeep"
- }
Now we create an index on the “Id” field with the expireAfterSeconds option.
db.Demo.createIndex({Name:1},{expireAfterSeconds:120 })
In the preceding example we create an index and set the value of expireAfterSeconds to 120. In other words, MongoDB removes the documnst after 120 seconds.
Sparse IndexThe Sparse option in an index ensures that the index only contains entries for documents that have the indexed field. It also removes documents containing null values. A non-sparse index contains all documents even if the documents don’t contain the indexed field. The index is “sparse” because it does not include all the documents of the collection.
Syntaxdb.Collection_Name.createIndex({fieldname:sorting_order}, { sparse: true })
ExampleThe Demo collection has the following documents.
- {
- "Id": 1,
- "Name": "Pankaj"
- } {
- "Id": 2,
- "Name": "Rahul"
- } {
- "Id": 3,
- "Name": "Sandeep"
- }
Now we create an index on the “Id” field with the sparse option.
db.Demo.createIndex({Name:1},{sparse:true })
In the preceding example we create an index and set the value of the sparse option to true.
Basic Index Methods
Now we consider some basic index methods.
getIndexes() MethodThe getIndexes() method retrieves all the existing indexes in a collection.
Suntaxdb.Collection_Name.getIndexes()
Exampledb.Demo.getIndexes()
Output
- [{
- "v": 1,
- "key": {
- "_id": 1
- },
- "name": "_id_",
- "ns": "Temp.Demo"
- }, {
- "v": 1,
- "key": {
- "Id": 1
- },
- "name": "Id_1",
- "ns": "Temp.Demo",
- "expireAfterSeconds": 1200
- }, {
- "v": 1,
- "key": {
- "Name": 1
- },
- "name": "Name_1",
- "ns": "Temp.Demo",
- "expireAfterSeconds": 12
- }]
dropIndex() MethodThe dropIndex() method removes a specific index from a collection.
Syntaxdb.Collection_Name.dropIndex({Field_Name})
Exampledb.Demo.dropIndex({"Id":1})
Output{ "nIndexesWas" : 3, "ok" : 1 }
In the preceding output “nIndexesWas” reflects the number of indexes before removing this index and “ok” execution status of command.
ensureIndex() Method
The ensureIndex() method creates an index. The ensureIndex() method only creates an index if an index of the same specification does not already exist.
Syntaxdb.Collection_Name.ensureIndex({field_name:sorting_order})
Exampledb.Demo.ensureIndex({"Id":1})
reIndex() MethodThe reIndex() method rebuilds the indexes for a collection. The reIndex() method first drops all the indexes, then rebuilds all the indexes.
Syntaxdb.Collection_Name.reIndex()
Exampledb.Demo.reIndex()
Output
- {
- "nIndexesWas": 3,
- "nIndexes": 3,
- "indexes": [{
- "key": {
- "_id": 1
- },
- "name": "_id_",
- "ns": "Temp.Demo"
- }, {
- "key": {
- "Name": 1
- },
- "name": "Name_1",
- "ns": "Temp.Demo",
- "expireAfterSeconds": 12
- }, {
- "key": {
- "Id": 1
- },
- "name": "Id_1",
- "ns": "Temp.Demo"
- }],
- "ok": 1
- }
Indexes.find() MethodThe indexes.find() method returns a list of all indexes on all collections of a database.
Syntaxdb.system.indexes.find()
Exampledb.system.indexes.find()
Output
- {
- "v": 1,
- "key": {
- "_id": 1
- },
- "name": "_id_",
- "ns": "Temp.Employee_Deatils"
- } {
- "v": 1,
- "key": {
- "_id": 1
- },
- "name": "_id_",
- "ns": "Temp.Employee_Details"
- } {
- "v": 1,
- "key": {
- "_id": 1
- },
- "name": "_id_",
- "ns": "Temp.pan"
- } {
- "v": 1,
- "key": {
- "_id": 1
- },
- "name": "_id_",
- "ns": "Temp.post"
- } {
- "v": 1,
- "key": {
- "_id": 1
- },
- "name": "_id_",
- "ns": "Temp.ram"
- } {
- "v": 1,
- "key": {
- "_id": 1
- },
- "name": "_id_",
- "ns": "Temp.Test"
- } {
- "v": 1,
- "key": {
- "_id": 1
- },
- "name": "_id_",
- "ns": "Temp.City_Info"
- } {
- "v": 1,
- "key": {
- "_id": 1
- },
- "name": "_id_",
- "ns": "Temp.Post"
- } {
- "v": 1,
- "key": {
- "_id": 1
- },
- "name": "_id_",
- "ns": "Temp.Employee"
- } {
- "v": 1,
- "key": {
- "Name": 1
- },
- "name": "Name_1",
- "ns": "Temp.Employee"
- } {
- "v": 1,
- "key": {
- "Likes": 1
- },
- "name": "Likes_1",
- "ns": "Temp.post"
- } {
- "v": 1,
- "key": {
- "Likedfs": 1
- },
- "name": "Likedfs_1",
- "ns": "Temp.post"
- } {
- "v": 1,
- "key": {
- "Likedfgdfs": 1
- },
- "name": "Likedfgdfs_1",
- "ns": "Temp.post"
- } {
- "v": 1,
- "key": {
- "Comment.CommentBy": 1
- },
- "name": "Comment.CommentBy_1",
- "ns": "Temp.po
- st"
- }
Today we learned about indexes, their types and some basic methods for indexes. In the next article we will learn about Aggregation.
Thanks for reading this article.