MongoDBIntermediate
Indexes
Unique, compound index এবং বড় collection-এ query দ্রুত করার উপায় — বাংলায়।
10টি অংশবাংলা ভাষায়
Index কী?
Index হলো ডেটাবেস-স্তরের একটি lookup structure যা query দ্রুত করে। ছোট collection-এ বোঝা যায় না, কিন্তু বড় collection-এ (আরো বেশি) index ছাড়া find পুরো collection scan করতে পারে।
Schema থেকে index
Single-field indexjs
js
const userSchema = new mongoose.Schema({
email: { type: String, required: true, unique: true }, // unique index
username: { type: String, unique: true },
createdAt: { type: Date, index: true }, // plain index
});Compound index
Composite indexjs
js
const orderSchema = new mongoose.Schema({
customer: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
status: String,
createdAt: Date,
});
// customer + status + createdAt — এই combo-তে query দ্রুত
orderSchema.index({ customer: 1, status: 1, createdAt: -1 });
// অথবা schema declaration-এও
// orderSchema.index({ customer: 1 });Index সেটআপ
syncIndexesjs
js
// ডেভেলপমেন্টে index তৈরি/সংশোধন করা হয়
await User.syncIndexes();
await Order.syncIndexes();
// production-এ migration সময় রান করুন, প্রতিদিন নয়Index design tips
- Equality field আগে, range field পরে রাখুন (যেমন
{ status: 1, createdAt: -1 }) - 1 = ascending, -1 = descending — sort direction-ও index-এ ভূমিকা রাখে
- প্রয়োজনের বেশি index না — প্রতিটি লেখা (write) index-ও আপডেট করে
- ডিবাগের জন্য
.explain("executionStats")দিয়ে দেখুন index ব্যবহার হচ্ছে কিনা
শেষ প্যারায় নিজে practice করুন — কোড কপি করে নিজের এডিটরে চালিয়ে দেখুন।