Role of Indexes in MongoDB
Indexes provide high performance read operations for frequently used queries. It includes indexes in MongoDB, describes the types and configuration options for indexes, and describes special types of indexing MongoDB supports. The section also provides tutorials detailing procedures and operational concerns, and providing information on how applications may use indexes.
Basically the indexes in MongoDB are similar to the indexes in other databases. These indexes are defined at the collection level and consists of indexes for many other fields and sub-fields in the documents. Indexing is used to limit the number of documents to be viewed to fasten the operations.
Consider following examples –
Types of Indexes in MongoDB
There are fundamentally six types of indexes supported by MongoDB –
Default _id : This is the default and unique index that exists in every collection. If there are no values assigned to the index, MongoDB creates an _id field with an ObjectId value.
Single Field : MongoDB supports user-defined indexes on a single field.
For example, db.userdetails.find().sort({“education”:1})
It is clear from the above example that the field education is sorting in the ascending order.
Compound Index : Not only single field but MongoDB supports user-defined indexes on multiple fields. The sequence of fields inside the compound index denotes certain order.
For example, in following example education will be sorted at first and then the password.
db.userdetails.find().sort({"education":1,"password":-1})
Multikey Index : MongoDB supports multikey indexes for the data stored in arrays. Each column index holds an array value and separate index values for the individual entries. This helps in matching the elements of the array.
Consider following example of a document within a collection where extra is an array, ‘friends’ and ‘ban_firends_id’ are the sub-arrays.
{
"_id" : ObjectId("528f34950fe5e6467e58ae77"),
"user_id" : "user1",
"password" : "1a2b3c",
"sex" : "Male",
"age" : 17,
"date_of_join" : "16/10/2010",
"education" : "M.C.A.",
"profession" : "CONSULTANT",
"interest" : "MUSIC",
"extra" : {
"friends" : {
"valued_friends_id" : [
"kumar",
"harry",
"anand"
],
"ban_friends_id" : [
"Amir",
"Raja",
"mont"
]
}
}
}
Geospatial Index : MongoDB allows to coordinate the geospatial data with the help of special indexes, i.e., 2d indexes and 2sphere indexes. These indexes are used in planar geometry.
Text Index : MongoDB also allows you to search the string content in a collection using the text indexes. These Text indexes so not store language-specific words or limit itself with root words
Hashed Index : MongoDB also supports hash-based sharding with the help of Hashed index which indexes the hash value of a field.