डिप्लोमा इन ऑफिस मैनेजमेंट एण्ड अकाउटिंग

डिप्लोमा इन ऑफिस मैनेजमेंट एण्ड अकाउटिंग

Full Stack Web Development with Laravel

Full Stack Web Development with Laravel

Affiliate Program

Affiliate Program

Compound index with simple example in mongodb

A compound index in MongoDB is an index that includes multiple fields. Unlike a single-field index that only indexes one field, a compound index allows you to create an index on multiple fields, which can improve query performance for queries that involve those fields.
 
Here is an example of a compound index in MongoDB:
 
Suppose we have a collection of users, and each document in the collection has a firstName and a lastName field. We want to create an index that allows us to query users by both their first name and last name. To do this, we can create a compound index on the firstName and lastName fields.
 
To create a compound index on these fields, we can use the createIndex() method in MongoDB:

db.users.createIndex({ firstName: 1, lastName: 1 })
This creates a compound index on the firstName and lastName fields, with both fields indexed in ascending order. This means that when we query the users collection by both fields, the index will be used to speed up the query.
 
For example, suppose we want to find all users with the first name 'John' and last name 'Doe':
db.users.find({ firstName: 'John', lastName: 'Doe' })
With a compound index on the firstName and lastName fields, this query can be executed more efficiently, because MongoDB can use the index to quickly locate the relevant documents.
 
It's worth noting that creating a compound index with more fields can improve query performance for queries that involve those fields, but it can also increase the index size and potentially slow down write operations. So, it's important to consider the tradeoffs when creating compound indexes, and to monitor the performance of your queries and indexes over time.
© 2016 - 2023, All Rights are Reserved.