MongoDB

MongoDB Indexing Example

Hello readers, in Mongo database, an index is a data structure that holds the specific data of the documents. In this tutorial, we will understand the Mongo database indexing to improve the performance of the search query.

1. Introduction

If you have installed the MongoDB application (version 3.6) on Windows or Ubuntu operating system and you wish to learn the indexing in Mongo database then follow the below steps. It is very simple. But before moving further let’s take a look at the Mongo database and its features.

1.1 What is MongoDB?

  • MongoDB is a high-performance NoSQL database where each database has collections which in turn has documents. Each document has a different number of fields, size, content, and is stored in a JSON-like format (i.e. Binary JSON (BSN)
  • The documents in MongoDB doesn’t need to have a schema defined beforehand. Instead, the fields (i.e. records) can be created on the go
  • Data model available within the MongoDB allows developers to represent the hierarchical relationships, store arrays, and other more complex structures easily
  • This NoSQL solution often comes with embedding, auto-sharding, and onboard replication for better scalability and high availability

1.2 Why MongoDB?

  • As a NoSQL type database, MongoDB stores the data in the form of a document. Thus, MongoDB offers more flexibility
  • This database supports search by field-name, range queries, and the regular expressions. It often provides queries to return the particular fields inside the documents
  • MongoDB offers indexes to improve the search performance within the NoSQL database
  • To offer horizontal scalability, MongoDB uses sharding by splitting the data across the many MongoDB occurrences
  • Replication: MongoDB can give high availability with the replica sets

1.3 Indexing in Mongo Database

Indexing in Mongo database is a data structure that stores the few fields of a document in a structure that is easy to traverse. This concept increases the search operations performance and helps in the following functions:

  • Search operation is performed on the indexes that hold only a set of data without a complete scan of the Mongo collection
  • Store the field values in the order of value
  • Support the range-based equality match queries

Fig. 1: Pictorial representation of an Index in the Mongo collection
Fig. 1: Pictorial representation of an Index in the Mongo collection

1.3.1 Types of Index in Mongo database

Below is the list of the indexes available in the Mongo database.

  • Default _id: Each document in a Mongo collection has an index on the default _id field. This index is unique and restricts clients from adding the two documents with the same value
  • Single Field: For a single field index, Mongo database can traverse the indexes either in the ascending or the descending order to do the sort operations
  • Compound Index: In order to support the multiple single fields, Mongo database uses the user-defined indexes, known as compound indexes. Mongo database limits the compound index fields to a maximum of 31
  • Multi-key Index: This index is used for indexing the field containing an array data i.e. mongo database will create an index for every value in an array
  • Geospatial Index: This index is used on the 2D indexes and 2D spherical indexes
  • Text Index: This index is used to search the data string in a Mongo collection
  • Hashed Index: This index is used to give the hash-based indexes and supports the hash-based sharding

1.3.2 How to create an Index in the Mongo database?

The below query syntax shows how to create an index in a Mongo collection.

Query Syntax

> db.collection_name.createIndex( { field_name: <sorting_value> } )

Where:

  • The field_name is the attribute name on which the index is created
  • The sorting_value is the value through which the sorting order is defined i.e. 1 for ascending order and -1 for descending order

2. MongoDB Indexing Example

In this tutorial, we will learn how to handle the single field index provided by the Mongo database. But before moving further with the tutorial, we will need to create the sample collection. The following script creates a database called warehouse with a collection as editors. Open the Mongo terminal and execute the script.

> use warehouse

> db.editors.insertMany( [
	{ "_id" : "101", "name" : "Daniel Atlas", "age": "26" }, 
	{ "_id" : "102", "name" : "Charlotte Neil", "age": "30" },
	{ "_id" : "103", "name" : "James Breen", "age": "32" },
	{ "_id" : "104", "name" : "John Gordon", "age": "24" },
	{ "_id" : "105", "name" : "Rick Ford", "age": "21" },
	{ "_id" : "106", "name" : "Susan Dixit", "age": "34" },
	{ "_id" : "107", "name" : "John Snow", "age": "31" },
	{ "_id" : "108", "name" : "Arya Stark", "age": "30" },
	{ "_id" : "109", "name" : "Smith William", "age": "27" },
	{ "_id" : "110", "name" : "John Daniel", "age": "29" }
] )

> db.editors.find().pretty()

If everything goes well, the database and the collection will be shown in the Mongo Workbench.

Fig. 2: Database &amp; Collection Creation
Fig. 2: Database & Collection Creation

2.1 Single Field Index in the Mongo database

In the Mongo universe, the database developers can create the ascending or the descending order of index on a single field in a collection. Developers can create a single key index as below and here is what the sample command will look like.

Command

> db.editors.createIndex( { "name": 1 } )

Where:

  • name is the attribute name on which the index is created in a collection
  • 1 is the value of the sorting order

This command will create an index based on the name attribute of the document. The 1 parameter indicates that the name field values should be sorted in an ascending order. Do remember, this is different from the default _id field and the Mongo documents will now be sorted as per the name field and not the _id field.

Fig. 3: Creating the Index in the Mongo database
Fig. 3: Creating the Index in the Mongo database

Here if developers search the document based on the name, the search operation will be faster as the indexing mechanism will be used for this search. Thus, indexing is important to create the index on the field that will be frequently searched in a collection.

2.1.1 Finding the indexes in a Mongo collection

Developers can use the getIndexes() method to find all the indexes created on a collection and here is what the sample command will look like.

Command

> db.editors.getIndexes()

This command displays the indexes that are available in a particular collection. Here, the default index is created on the _id field and the user index will be on the name field.

Fig. 4: Finding the indexes in a Mongo collection
Fig. 4: Finding the indexes in a Mongo collection

2.1.2 Dropping the indexes in a Mongo collection

Developers can either drop a particular index or all the indexes in a collection. In order to drop a particular index, the following sample command is used.

Command

> db.editors.dropIndex( { name: 1 } )

Where:

  • name is an input argument that works as the index_name

This command displays the information about the existing indexes and the "ok" : 1 output means the command is executed successfully.

Fig. 5: Dropping a specific index in a Mongo collection
Fig. 5: Dropping a specific index in a Mongo collection

In case, developers wish to drop all the indexes of a collection, they can use the dropIndexes() method and here is what the query syntax will look like.

Syntax

> db.collection_name.dropIndexes()

Fig. 6: Dropping all indexes in a Mongo collection
Fig. 6: Dropping all indexes in a Mongo collection

Do remember, using this command a developer can only drop the indexes that are created by a developer, but they cannot drop the default index created on the _id field. That’s all for this post. Happy Learning!!

3. Conclusion

In this tutorial, we learned about the indexes in the Mongo database. Developers can download the sample commands in the Downloads section.

4. Download the Eclipse Project

This was an example of indexing in the Mongo database.

Download
You can download the full source code of this example here: MongoDbIndexing

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button