Indexing-Sharding and Replication in MongoDB
Indexing-Sharding and Replication in MongoDB
Replication in
MongoDB
By – Jigna Patel
MongoDB Indexes
• Indexes are special data structures that store a small part of the
Collection’s data in a way that can be queried easily.
• In simplest terms, indexes store the values of the indexed fields
outside the table or collection and keep track of their location in the
disk. These values are used to order the indexed fields.
• This ordering helps to perform equality matches and range-based
query operations efficiently. In MongoDB, indexes are defined in the
collection level and indexes on any field or subfield of the documents
in a collection are supported.
Creating indexes
• When creating documents in a collection, MongoDB creates a unique
index using the _id field. MongoDB refers to this as the Default _id Index.
This default index cannot be dropped from the collection.
• see the _id field which will be
• utilized as the default index:
• Syntax : db.<collection>.createIndex(<Key and Index Type>, <Options>)
• When creating an index, you need to define the field to be indexed and the
direction of the key (1 or -1) to indicate ascending or descending order.
• Indexes cannot be renamed after creation. (The only way to rename an index is
to first drop that index and recreate it using the desired name.)
• Let’s create an index using the name field in the studentgrades collection and
name it as student name index.
Finding indexes
• You can find all the available indexes in a MongoDB collection by using the
getIndexes method.
• Syntax: db.<collection>.getIndexes()
Dropping indexes
You can use the sort() method to see how the data will be
represented in the index.
Compound index
• You can use multiple fields in a MongoDB document to create a compound index.
• This type of index will use the first field for the initial sort and then sort by the
preceding fields
1. Geospatial Index
• MongoDB provides two types of indexes to increase the efficiency of database queries
when dealing with geospatial coordinate data:
• 2d indexes that use planar geometry which is intended for legacy coordinate pairs used in
MongoDB 2.2 and earlier.
• 2dsphere indexes that use spherical geometry.
2. Text index
• The text index type enables you to search the string content in a collection.
3. Hashed index
• MongoDB Hashed index type is used to provide support for hash-based
sharding functionality. This would index the hash value of the specified field.
Sharding
What is sharding?
• Sharding is the process of distributing data across multiple hosts. In
MongoDB, sharding is achieved by splitting large data sets into small
data sets across multiple MongoDB instances.
How sharding works…
When dealing with high throughput applications or very large
databases, the underlying hardware becomes the main limitation. High
query rates can stress the CPU, RAM, and I/O capacity of disk drives
resulting in a poor end-user experience.