logo
Explore Our Blog Posts
HomeBlogMongoDB Query Slow? Creating Index is Not Always the Solution!

Explore Our Blog Posts

MongoDB Query Slow? Creating Index is Not Always the Solution!

কবে index করবেন আর কবে করবেন না?

Mamunur Rashid Mamun

Mamunur Rashid Mamun

16 Jun, 2025

MongoDB

MongoDB Query Slow? Creating Index is Not Always the Solution!
MongoDB Query Slow? Creating Index is Not Always the Solution!

MongoDB-তে query slow হলে প্রথমেই আমরা index তৈরি করে ফেলি। কিন্তু ভুল জায়গায় index পারফরম্যান্স খারাপ করে দিতে পারে!


🤷‍♂️ তাহলে কবে index করবেন আর কবে করবেন না?

✔️ কবে Index করবেন:
-> যখন একটি ফিল্ডে আপনি অনেক find, sort, বা filter করছেন।
-> যদি query-তে result খুব কম document রিটার্ন করে (low selectivity), index বেশি কার্যকর।
-> Compound index যখন multiple fields একসাথে frequent query-তে ব্যবহৃত হয়।
-> Covered query যখন index fields থেকেই সব result পাওয়া যায়, তখন performance দ্রুত হয়।

❌ কবে Index করবেন না:
-> যখন আপনার ফিল্ডের value গুলো প্রায় সবসময় same (e.g., gender, status with few possible values)।
-> Frequently updated fields-এ index রাখলে write-heavy অ্যাপে performance degrade হয়।
-> Low cardinality fields, index help করে না, শুধু storage নেয়।


📌 Example:

একটি Logistics Tracking অ্যাপে আমরা প্রতিটি পার্সেলের statusHistory নামে একটি array রাখতাম, যেখানে প্রতিটি item ছিল একটি embedded document:
 

{
    parcelId: "P12345",
    statusHistory: [
        { status: "Dispatched", timestamp: "2025-06-10T10:00:00Z" },
        { status: "In Transit", timestamp: "2025-06-11T08:30:00Z" },
        ...
    ]
}


আমরা চাচ্ছিলাম প্রতিটি পার্সেলের সর্বশেষ status খুঁজে পেতে।
প্রথমে আমরা statusHistory.timestamp ফিল্ডে index দিয়েছিলাম, মনে করেছিলাম sort করলেই performance ভালো হবে।

Problem?
-> MongoDB compound index array field-এ কাজ করে না যেভাবে আমরা ভাবি। Index শুধু array-র প্রথম কয়েকটি item-এ কাজে লাগে।
-> আর aggregation pipeline-এ $slice বা $last ব্যবহার করায় index কাজে লাগছিল না।

Result?
❌ Query slow
❌ Index space wasted