0Pricing
MongoDB Academy · درس

إنشاء فهارس أحادية الحقل ومركبة

سينشئ المتعلمون فهارس أحادية الحقل وفهارس مركبة، ويراقبون تغييرات خطة الاستعلام باستخدام explain('executionStats').

إنشاء فهارس أحادية الحقل ومركبة درس مجاني في MongoDB Academy على CoddyKit. هذا هو الدرس 2 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في MongoDB Academy، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة MongoDB Academy 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

Single-Field Index Basics

A single-field index is the simplest index type: it tracks the values of exactly one document field in a sorted B-tree. You create one with db.collection.createIndex({ field: 1 }), where 1 means ascending order and -1 means descending. Single-field indexes are ideal for queries that filter or sort on just one field.

// Create a single-field ascending index on 'email'
db.users.createIndex({ email: 1 });

// This query now hits the index instead of scanning every document
db.users.find({ email: 'alice@example.com' });

Naming Your Indexes

MongoDB auto-generates an index name like email_1 or age_-1 from the field name and direction. You can override this with the name option to give meaningful labels to your indexes—especially helpful when managing many indexes in production or when the auto-generated name would exceed the 127-character limit imposed on compound indexes with many fields.

db.users.createIndex(
  { email: 1 },
  { name: 'idx_users_email' }
);

// List all indexes with their names
db.users.getIndexes();

What Is a Compound Index?

A compound index tracks multiple fields together in a single B-tree. The entries are sorted first by the first field, then by the second field within each group of the first, and so on. This makes compound indexes far more selective and versatile than multiple single-field indexes for queries that filter or sort on several fields at once.

// Compound index on lastName (asc) then firstName (asc)
db.users.createIndex({ lastName: 1, firstName: 1 });

// This single index satisfies all three queries efficiently:
db.users.find({ lastName: 'Smith' });
db.users.find({ lastName: 'Smith', firstName: 'John' });
db.users.find({}).sort({ lastName: 1, firstName: 1 });

The Prefix Rule for Compound Indexes

A compound index on { a, b, c } can serve queries on { a }, { a, b }, and { a, b, c }—these are called index prefixes. It cannot serve a query on just { b } or { c } alone because the B-tree is ordered by the first field first. Understanding the prefix rule helps you avoid creating redundant single-field indexes when a compound index already covers them.

db.orders.createIndex({ userId: 1, status: 1, createdAt: -1 });

// Supported by the compound index (prefixes):
db.orders.find({ userId: 'u1' });
db.orders.find({ userId: 'u1', status: 'pending' });
db.orders.find({ userId: 'u1', status: 'pending' }).sort({ createdAt: -1 });

// NOT supported - skips the first key
db.orders.find({ status: 'pending' }); // still does COLLSCAN

Creating a Compound Index

You create a compound index by passing an object with multiple fields to createIndex. Field order matters: put equality fields first (fields filtered with $eq or exact values), then range fields, then sort fields. This arrangement ensures the index is used for both filtering and sorting in one traversal, following the ESR (Equality, Sort, Range) principle.

// Orders queried by userId (equality), sorted by date (sort),
// then filtered by amount (range)
// ESR order: userId -> createdAt -> amount
db.orders.createIndex({ userId: 1, createdAt: -1, amount: 1 });

// Perfectly served by this index:
db.orders
  .find({ userId: 'u123', amount: { $gt: 100 } })
  .sort({ createdAt: -1 });

Using explain() to See Index Usage

Always verify that your new index is actually being used with .explain('executionStats'). Look for winningPlan.stage: 'IXSCAN' to confirm index use, and check totalDocsExamined vs nReturned—a well-indexed query should examine roughly the same number of documents it returns.

const result = db.orders.find(
  { userId: 'u123' }
).explain('executionStats');

// Key fields to check:
// result.executionStats.executionStages.stage === 'IXSCAN'
// result.executionStats.totalDocsExamined
// result.executionStats.nReturned

Background Index Builds

In MongoDB 4.2+, all index builds are non-blocking by default: they hold an exclusive lock only briefly at the start and end of the build, allowing reads and writes to continue during the lengthy build phase. On older versions you had to specify { background: true } explicitly. Building a large index can still consume significant CPU and I/O resources, so schedule builds during low-traffic periods in production.

// MongoDB 4.2+: non-blocking by default
db.bigCollection.createIndex({ category: 1 });

// Check ongoing index builds
db.currentOp({ 'command.createIndexes': { $exists: true } });

Dropping Indexes

You can remove an index with db.collection.dropIndex(), passing either the index name or the key specification. Dropping unused indexes reduces write overhead and frees memory. The _id index cannot be dropped. Use dropIndexes() (plural) to drop all non-_id indexes at once—useful when rebuilding an index strategy from scratch.

// Drop by name
db.users.dropIndex('idx_users_email');

// Drop by key pattern
db.users.dropIndex({ email: 1 });

// Drop all except _id
db.users.dropIndexes();

// List remaining indexes
db.users.getIndexes();

Index Statistics With $indexStats

$indexStats is an aggregation stage that shows how many times each index has been used since the mongod process last started. An index with zero accesses is a prime candidate for removal. Combine this data with the index size from db.collection.stats() to build a complete cost/benefit picture for each index in your collection.

db.orders.aggregate([
  { $indexStats: {} },
  { $project: {
    name: 1,
    'accesses.ops': 1,
    'accesses.since': 1
  }}
]);

Compound vs Multiple Single Indexes

Multiple single-field indexes can sometimes be combined via index intersection, but MongoDB's planner prefers compound indexes when they exist. A single well-designed compound index is almost always faster and more predictable than relying on the planner to intersect two separate indexes. Create compound indexes for your most frequent multi-field queries rather than hoping intersection will save you.

// Less ideal: two separate indexes
db.products.createIndex({ category: 1 });
db.products.createIndex({ price: 1 });

// Better: one compound index for the common query pattern
db.products.createIndex({ category: 1, price: 1 });

The 64 Indexes Per Collection Limit

MongoDB allows a maximum of 64 indexes per collection. This is more than enough for well-designed schemas, but if you approach this limit, it is a strong signal that something is wrong—perhaps you have many redundant indexes or a table-like design that doesn't fit the document model. Audit your index usage regularly and prune indexes that have zero $indexStats accesses.

// See how many indexes your collection has
const indexes = db.myCollection.getIndexes();
console.log('Index count:', indexes.length);

// Hard limit: 64 indexes per collection
// Approaching it? Audit with $indexStats first

Quick Check

Test your understanding of single-field and compound indexes in MongoDB.

Lesson Recap

In this lesson you learned: single-field indexes track one field in a sorted B-tree and support equality, range, and sort queries, compound indexes track multiple fields and must be queried using their prefixes, and ESR ordering (Equality, Sort, Range) maximises compound index effectiveness. Next up we explore special index properties like unique, sparse, partial, and TTL.

الأسئلة الشائعة

هل درس «إنشاء فهارس أحادية الحقل ومركبة» مجاني؟

نعم — نص درس «إنشاء فهارس أحادية الحقل ومركبة» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة MongoDB Academy، انتقل إلى CoddyKit PRO. تتضمن دورة MongoDB Academy 4 دروس في المجموع.

ماذا ستتعلم في «إنشاء فهارس أحادية الحقل ومركبة»؟

سينشئ المتعلمون فهارس أحادية الحقل وفهارس مركبة، ويراقبون تغييرات خطة الاستعلام باستخدام explain('executionStats'). تتمرن على MongoDB Academy مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ MongoDB Academy؟

لا تُشترط خبرة سابقة. MongoDB Academy على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 2 من أصل 4.

كم من الوقت يستغرق درس «إنشاء فهارس أحادية الحقل ومركبة»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس MongoDB Academy هذا؟

نعم. كل درس في MongoDB Academy يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. كيفية عمل فهارس B-Tree في MongoDB
  2. إنشاء فهارس أحادية الحقل ومركبة
  3. خصائص الفهارس: فريدة، متناثرة، جزئية، وTTL
  4. قراءة مخرجات explain() لتشخيص الاستعلامات
← العودة إلى MongoDB Academy