How do I know which fields to index in MongoDB?
Index fields you query often: email for login, userIds for fetching a user's data, and foreign keys. For multi-field queries, use compound indexes. For sorts, index the sort field. Use the explain method to confirm indexes are used.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in MongoDB Indexing Best Practices for Node.js Apps
An index on multiple fields together, like { status: 1, age: 1 }. Use it when you query on multiple fields together, like { status: 'active', age: { $gt: 18 } }. The order of fields in the compound index matters for query performance.
Run User.find(query).explain('executionStats'). If it shows IXSCAN, the index is used. If it shows COLLSCAN, MongoDB is scanning the entire collection, which means your index is not being used for this query.
An index that enforces uniqueness at the database level. For fields that must be unique like email, create a unique index with { unique: true } in the schema. This prevents duplicate values, not just in your code but in the database itself.
Still have questions?
Browse all our FAQs or reach out to our support team
