Indexing and Search

MongoDB Indexing and Search

Indexes are the key to MongoDB performance. They dramatically speed up your queries. Without them, MongoDB must scan every single document.

What is an Index?

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.

The Default _id Index

MongoDB creates one index automatically. Every collection has an index on the _id field. This guarantees fast lookups by primary key.

Creating a Single Field Index

You can add indexes to any field you query often. Use createIndex() to build one. Sorting by 1 is ascending, -1 is descending.

Compound Indexes

A compound index includes multiple fields. It supports queries that match several conditions. The order of fields in a compound index matters heavily.

Indexing Example:

// 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

Unique indexes prevent duplicate data entirely. They enforce rules like unique emails or usernames. MongoDB rejects any insert that breaks the unique rule.

Atlas Search

Standard indexes handle exact matches well. For advanced text queries, use Atlas Search. It incorporates a powerful Lucene search engine natively.

Analyzing Queries

Always verify that your indexes are working. Use the explain() method on your queries. It details exactly which index was chosen by the engine.

Summary

Indexes prevent slow collection scans. Add indexes to fields used in $match or sort logic. Use unique indexes to enforce clean data requirements.

Exercise

What does MongoDB have to do if a query does not use an index?