What is Indexing in MongoDB and how to use it?
indexing in MongoDB
First, let's discuss what indexing is and why we need it. Indexing plays a crucial role in enhancing query performance within databases.
What is Indexing?
Indexing is a technique used to speed up query execution by providing efficient access to data within a database. It involves creating data structures that allow for rapid data retrieval based on the values in one or more columns. Rather than scanning the entire dataset, indexing helps narrow down the search to specific rows, significantly reducing query times.
How Does Indexing Work in MongoDB?
MongoDB uses indexing to optimize the retrieval of data. When an index is created, it effectively generates a B-tree-like structure in which the indexed field values are organized. This structure enables MongoDB to locate data more swiftly, without the need to scan every document in the collection.
#collection { "_id": ObjectId("61799a9b177b3d53f85e14c0"),
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald",
"genre": "Fiction", "published_year": 1925,
"ratings": [4.5, 4.2, 3.8],
"reviews": [ { "user": "reader123", "rating": 4.5, "comment": "A classic novel with vivid characters." },
{ "user": "booklover456", "rating": 4.2, "comment": "Enjoyed the rich storytelling." } ],
"tags": ["Classic", "Fiction"] }
The types of indexing are:-
- Single Field Index-creating indexing on a single field within the collection
db.books.createIndex({ title: 1 }); // Creating a single field index on 'title'
- Compound indexing- create indexing on multiple fields together, it is useful when queries involve multiple criteria
db.books.createIndex({ genre: 1, published_year: 1 }); // Creating a compound index
- mulitkey indexing - used when dealing with an array or sub-document within the document it creates an indexing on each element of an array.
db.books.createIndex({ tags: 1 }); // Creating a multikey index on 'tags'
- Text indexing - used when we have to create indexing based on text search.
db.books.createIndex({ title: "text", "reviews.comment": "text" }); // Creating a text index
These are some basics about MongoDB Indexing. Adance will come next week
I hope you found this blog useful. If so, please consider sharing it with your friends and I would appreciate your feedback. You can also reach out to me on Twitter at @lalitaswal2, and I would be happy to hear your thoughts.