Imagine you run a busy online store using MongoDB. What is the main reason to focus on performance tuning?
Think about what users feel when the website is slow.
Performance tuning helps queries run faster, which means users get their data quickly and have a better experience.
You have a collection 'orders' with 1 million documents. You run this query:
{ customerId: 12345 }Without an index on 'customerId', the query takes 10 seconds. With an index, it takes 0.1 seconds.
What is the main reason for this difference?
Think about how you find a word in a book with or without an index.
An index works like a book's index, letting MongoDB jump directly to matching documents instead of checking every one.
You want to force MongoDB to use the index named 'customerId_1' for this query:
db.orders.find({ customerId: 12345 })Check MongoDB documentation for the method to specify an index.
The hint() method tells MongoDB which index to use for the query.
You have a large collection with many fields. You want to speed up queries that only need 'customerId' and 'orderDate'. What should you do?
Think about indexing only what you need and returning less data.
A compound index on the queried fields plus projection reduces data scanned and returned, improving speed.
Given the collection 'orders' with an index on 'customerId', this query runs slowly:
db.orders.find({ customerId: { $gt: 1000 } })What is the most likely reason?
Think about how range queries work with indexes.
Range queries like $gt use the index but may scan many entries, so performance depends on data distribution.