Updated March 23, 2023
Introduction to MongoDB creates Index.
Mongo DB creates Index, Indexes in DBMS help increase the performance of queries like fetching and updating data. MongoDB is used by complex data mining, data analytics algorithms to manage, modify and arrange the data they work on. The data they deal with is humongous and require efficient handling. Imagine a collection that has hundreds of documents. To find documents that match a particular filter, MongoDB would have to match the filter against all the documents present in the collection, which is tedious and time-consuming. Instead of indexing documents(fields) will reduce the search time significantly. Indexes are data structures that are packed with partial data set within itself. The index stores the value of a particular field(s) in documents in an orderly fashion that supports operations such as comparators, equators, and range-based queries in sequential order.
Syntax to Create Index
db.collectionName.createIndex(<key and index type specification>, <options>)
Keys | Keys is a document that contains a field value pair where the field is index key and value is the type of index.
For example, value is 1 for sorting index key in ascending order and -1 in descending order. |
Options | Option(s) is a document that contains a set of options that influences the creation of indexes. These options are optional. |
Types of MongoDB Indexes
Here are the types of Indexes mention below:
1. Default id
Each document present in the Mongo collection contains an index default called “_id”. An object id is created while creating the document if no index values are present.
2. Single field
Indexing is performed on a single field, and sort operation is either ascending or descending as MongoDB can traverse in either direction.
Example:
db.collection.createIndex({"age":1})
3. Compound Index
MongoDB supports user-defined indexes in multiple fields. The order of the fields given in the compound index is quite significant. Sorting order takes from left to right, priority w.r.t to the first field mentioned in the compound indexes is higher to that of the next one.
Example:
db.collection.createIndex({“age”:1,”dim.h”:-1})
In this example, all the documents with age field are first sorted in ascending order and then descending order of height in dim.
4. Multikey Index
MongoDB uses Multikey Index to index data that is in an array format. While indexing, each element in the array is created a separate index, and the data is indexed based on the element(s) present in the array. MongoDB takes care if the index field has an array in it by default.
5. Geospatial Index
MongoDB uses Geospatial indexing to find data based on its location. It supports two types of searching, 2D(two dimensional) and 3D(three dimensional). These indexes are used to get results within a range. The number of search results can also be limited by using limit(<Number>) function.
Example:
db.players.find({ loc:{ $near: { $geometry: { type: "high_school",sport:"basketball " age: [14, 17]} } } })
This example will find all the entries of students in high_school, play basketball, and are within the age range of 14 to 17.
6. Text Index
MongoDB provides Text indexing to support queries in string format. Text index can have any fields which consist of string elements or an array of string elements.
Example:
db.movies.find( { $text : { $search : "tom hardy" } } )
This example will find all the documents that have actor names like tom hanks, Tom Felton, Tom Hiddleston as well as Robert hardy and john hardy. MongoDB takes in the string provided for search and gives all the documents with a complete or partial search string.
7. Hashed Index
MongoDB uses a hashed index to support sharding. Hashing indexes calculates the hash value of the index fields using a hash function. It does not support multi-key indexing (array values). Hash indexes are created using createIndex function, and the value of the index field should always be ‘hashed’.
Example:
db.collection.createIndex( {<fieldname>: "hashed" } )
To find the documents with hash values, db.collection.find( { <fieldname>: Math.pow(2,63) } ) will return all the documents with hash indexes in the range 2^63.
Options for Indexing
1. Unique index
As the name suggests, unique indexes are unique in nature. MongoDB does not allow duplicate values if an index is created using the “unique” option.
To specify that an index is unique while creating the index, the following format should be used:
db.collection.createIndex( <key and index>, { unique: true } )
The unique constraints can be imposed on the compound index, multikey index, and text index as well.
2. Partial index
Partial indexes index documents of a collection based on a specific filter or expression. Since partial indexes index, only a subgroup of the collection space(memory) requirements are less, resulting in reduced performance.
Example:
db.pupils.createIndex( { name: 1},{ partialFilterExpression: {age: { $gt: 5 } } }
Filter expressions supported:
- $gt, $gte, $lt, $lte (greater than, greater than or equal, less than and less than or equal)
- $type operators
- $exists : true operation
- Equality operator ($eq)
- Logical and, or operations
3. TTL index
TTL indexes a special kind of single key indexes that can be deleted from the MongoDB collection after a timeout or at a specific clock time. Some applications that log machine-generated data or logs that would eventually be invalid after some period of time find this very helpful.
Example:
db.log.createIndex( { "lastModifiedDate": 1 }, { expireAfterSeconds: 10000 } )
4. Sparse index
Sparse indexes index only the documents that contain the field value of the index. It ignores all the other documents that don’t contain the field. By default, non-sparse indexes contain all the documents in the collections, with null as the value for those fields which are not present.
Example:
db.pupil.createIndex( { "age": 1 }, { sparse: true } )
The index does not index documents that do not contain the field age.
5. Case insensitive index
Case insensitive indexes are used to support queries that execute string comparisons without any respect to Case sensitivity.
Example:
db.collection.createIndex( { "key" : 1 },{ collation: <collation options>} )
Collation:
Collation document is used to specify language rules, letter case, etc., for string comparison.
Collation documents consist of the following :
Conclusion – MongoDB Create Index
In conclusion, indexing is crucial for faster execution of queries and memory management. Indexes can be created, modified according to the requirements of users and dropped when not needed.
Recommended Articles
This is a guide to MongoDB create Index. Here we discuss the introduction to MongoDB create Index along with the types of indexes and options for indexing along with the respective examples. You may also look at the following article to learn more –