Facebook Pixel

What is the index prefix rule in MongoDB?

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.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in Compound Indexes in MongoDB Explained

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.

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

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.