| by Arround The Web | No comments

How to Improve Queries with MongoDB Indexing

Enhancing query speed is essential for MongoDB and all other database systems. By building data structures that help MongoDB identify records more rapidly, indexing is a potent approach to speeding up and optimizing searches. Indexes include copies of some of the data from records to make inquiries more effective. This streamlines the effort involved in responding to requests in MongoDB. In this guide, we will discuss the use of indexes with the help of different indexing types.

Create Collection

Before using indexes, we have to create a new collection in our MongoDB. We have already created one and inserted 10 documents, named “Dummy”. The find() MongoDB function displays all the records from the “Dummy” collection on the MongoDB shell screen below.

test> db.Dummy.find()

Choose Indexing Type

Before establishing an index, you must first determine the columns that will be commonly utilized in query criteria. Indexes perform well on columns that are frequently filtered, sorted, or searched. Fields with a large cardinality (many different values) are often excellent indexing options. Here are some code examples for different index types.

Example 01: Single Field Index

It’s probably the most fundamental type of index, which indexes a single column to enhance query speed on that column. This type of index is used for queries in which you use a single key field to query the collection records. Assume that you use the “type” field to query the records of the collection “Dummy” within the find function as below. This command would look through the whole collection, which might take a long time for huge collections to process. Hence, we need to optimize the performance of this query.

test> db.Dummy.find({type: "emp"})

The records of the Dummy collection above have been found using the “type” field i.e. containing a condition. Therefore, the single-key index can be utilized here to optimize the search query. So, we will be employing the createIndex() function of MongoDB to create an index on the “type” field of the “Dummy” collection. The illustration of using this query displays the successful creation of a single-key index named “type_1” on the shell.

test> db.Dummy.createIndex({ type: 1 })

Let’s use the find() query once it gains utilizing the “type” field. The operation will be significantly faster now than the previously used find() function as the index is in place because MongoDB can utilize the index to rapidly retrieve the records with the requested job title.

test> db.Dummy.find({type: "emp"})

Example 02: Compound Index

We may want to look for items based on various criteria in certain circumstances. Implementing a compound index for these fields can help improve query performance. Let’s say, this time, you want to search from the collection “Dummy” using multiple fields containing different searching conditions as the query displays. This query has been searching for records from the collection where the “type” field is set to “emp,” and the “sal” field is greater than 350.

The $gte logical operator has been used to apply the condition to the “sal” field. A total of two records were returned after searching through the whole collection, which consists of 10 records.

test> db.Dummy.find({type: "emp", sal: {$gte: 350} })

Let’s create a compound index for the aforementioned query. This compound index has “type” and “sal” fields. The numbers “1” and “-1” represent ascending and descending order, respectively, for the “type” and “sal” fields. The sequence of the compound index’s columns is important and should correspond to the query patterns. The MongoDB has given the name “type_1_sal_-1” to this compound index as displayed.

test> db.Dummy.createIndex({ type: 1, sal: -1 })

After using the same find() query to search for records with the “type” field value as “emp” and the value of “sal” field greater than equal to 350, we have obtained the same output with a slight change in the order compared to the previous query result. The larger value record for the “sal” field is now at first place, while the smallest is at the lowest according to the “-1” set for the “sal” field in the compound index above.

test> db.Dummy.find({type: "emp", sal: {$gte: 350} })

Example 03: Text Index

Sometimes, you may encounter a situation in which you should deal with a large data set, like big descriptions of products, ingredients, etc. A text index might be useful for doing full-text searches on a big text field. For instance, we have created a new collection named “Test” within our test database. Inserted a total of 6 records in this collection using the insertMany() function as per the find() query below.

test> db.Test.insertMany([

{name: "Ana", des: "She lives in London and is a good teacher"},

{name: "Robert", des: "He is such an awesome Football player"},

{name: "Tina", des: "Might be travelling Dubai"},

{name: "Jacob", des: "He is mindblowing and rich."},

{name: "Cillian", des: "A movie super start just got fame in no seconds"},

{name: "Ken", des: "Food lover. She can eat you as well."}

])

Now, we will create a text index on the “Des” field of this collection, employing MongoDB’s createIndex() function. The keyword “text” in the field value displays the type of an index, which is a “text” index. The index name, des_text, has been autogenerated.

test> db.Test.createIndex({ des: "text" })

Now, the find() function has been used to perform the “text-search” on the collection via the “des_text” index. The $search operator was utilized to search for the word “food” in the collection records and display that particular record.

test> db.Test.find({ $text: { $search: "food" }});

Verify Indexes:

You can check and list down all the applied indexes of different collections in your MongoDB. For this, use the getIndexes() method along with the name of a collection in your MongoDB shell screen. We have used this command separately for the “Test” and “Dummy” collections. This shows all the necessary information regarding the built-in and user-defined indexes on your screen.

test> db.Test.getIndexes()

test> db.Dummy.getIndexes()

Drop Indexes:

It’s time to delete the indexes that were previously created for the collection using the dropIndex() function along with the same field name the index had been applied to. The below query shows that the single index has been removed.

test> db.Dummy.dropIndex({type: 1})

In the same way, the compound index can be dropped.

test> db.Dummy.drop index({type: 1, sal: 1})

Conclusion

By speeding up the retrieval of data from MongoDB, indexing is essential for enhancing the efficiency of queries. Lacking indexes, MongoDB must search the whole collection for matching records, which becomes less effective as the set’s size increases. MongoDB’s ability to swiftly discover the right records utilizing the index database structure speeds up the processing of queries when suitable indexing is used.

Share Button

Source: linuxhint.com

Leave a Reply