Indexing Introduction

Indexing Introduction

Indexes support the efficient execution of queries in MongoDB. Without indexes MongoDB must scan every document in a collection to select those documents that match the query statement. These collection scans are inefficient because they require mongod to process a larger volume of data than an index for each operation. Indexes are special data structures (B-tree data structure) that store a small portion of the collection’s data set in an easy to traverse form. The index stores the value of a specific field or set of fields, ordered by the value of the field.

Fundamentally, indexes in MongoDB are similar to indexes in other database systems. MongoDB defines indexes at the collection level and supports indexes on any field or sub-field of the documents in a MongoDB collection. If an appropriate index exists for a query, MongoDB can use the index to limit the number of documents it must inspect. In some cases, MongoDB can use the data from the index to determine which documents match a query. The following diagram illustrates a query that selects documents using an index.

Image 17

The diagram shows a query selecting documents using an index. MongoDB narrows the query by scanning the range of documents with values of score less than 30. It is suggested to create indexes to support common and user-facing queries. Having these indexes will ensure that MongoDB only scans the smallest possible number of documents. Indexes can also optimize the performance of other operations in specific situations

Sorted Results – MongoDB can use indexes to return documents sorted by the index key directly from the index without requiring an additional sort phase.

Image 18

The diagram shows a query that uses an index to select and return sorted results. The index stores score values in ascending order. MongoDB can traverse the index in either ascending or descending order to return sorted results.

Covered Results – When the query criteria and the projection of a query include only the indexed fields, MongoDB will return results directly from the index without scanning any documents or bringing documents into memory. These covered queries can be very efficient. Indexes can also cover aggregation pipeline operations.

Image 19

The diagram of a query that uses only the index to match the query criteria and return the results. MongoDB does not need to inspect data outside of the index to fulfill the query.

Apply for MongoDB Certification Now!!

https://www.vskills.in/certification/databases/mongodb-server-administrator

Back to Tutorial

Share this post
[social_warfare]
Data Model Examples and Patterns
Index Types

Get industry recognized certification – Contact us

keyboard_arrow_up