What is a compound index in MongoDB?
An index on two or more fields. MongoDB can use it for queries that filter on any prefix of the indexed fields. Example: index on (fromUserId, toUserId) works for fromUserId alone or fromUserId + toUserId, but not toUserId alone.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Compound Indexes in MongoDB Explained
A compound index on (A, B, C) can be used for A, A+B, or A+B+C. It cannot be used for B, C, or B+C. If you query on B+C, you need a separate index on (B, C) or a different compound index that starts with B.
By the ESR rule: Equality (exact match) first, Sort second, Range last. For a query like { fromUserId: X, age: { $gte: 18 } }.sort({ createdAt: -1 }), the index would be { fromUserId: 1, createdAt: -1, age: 1 }.
Call .explain('executionStats') on your query. Look at executionStats.totalDocsExamined. If it equals the collection size, the index is not used. If it is small, the index is working.
Still have questions?
Browse all our FAQs or reach out to our support team
