Indexes are the key to MongoDB performance. They dramatically speed up your queries. Without them, MongoDB must scan every single document.
An index is a special data structure. It stores a small portion of the collection's data. It is heavily optimized for quick traversal and sorting.
MongoDB creates one index automatically. Every collection has an index on the _id field. This guarantees fast lookups by primary key.
You can add indexes to any field you query often. Use createIndex() to build one. Sorting by 1 is ascending, -1 is descending.
A compound index includes multiple fields. It supports queries that match several conditions. The order of fields in a compound index matters heavily.
// Create an index on the email field
db.users.createIndex({ email: 1 });
// Create a compound index
db.users.createIndex({ lastName: 1, age: -1 });
// Force uniqueness on an index
db.users.createIndex({ username: 1 }, { unique: true });
Unique indexes prevent duplicate data entirely. They enforce rules like unique emails or usernames. MongoDB rejects any insert that breaks the unique rule.
Standard indexes handle exact matches well. For advanced text queries, use Atlas Search. It incorporates a powerful Lucene search engine natively.
Always verify that your indexes are working. Use the explain() method on your queries. It details exactly which index was chosen by the engine.
Indexes prevent slow collection scans. Add indexes to fields used in $match or sort logic. Use unique indexes to enforce clean data requirements.
What does MongoDB have to do if a query does not use an index?