Course contentsShow
← Computer Science
Lesson 1723 of 2,87239. NoSQL and Modern DatabasesFree lesson

Indexing Document Fields

Creating indexes on document fields, including compound indexes and indexes on nested fields for query performance.

Indexing Document Fields

What you'll learn: How to create indexes on document fields—including compound and nested fields—to dramatically speed up queries in document databases.

Why Index Document Fields?

Just like you've seen with B-tree and hash indexes in relational databases, document databases need indexes to avoid scanning every document when querying. Without indexes, finding documents that match {status: "active"} means reading every single document in your collection—painfully slow at scale.

Creating Simple Field Indexes

When you create an index on a document field (say, email), the database builds a lookup structure that maps values to documents. Now queries filtering on email run in logarithmic or constant time instead of linear.

Think of it like a book's index: Instead of flipping through every page to find mentions of "databases," you check the index and jump straight to page 42.

Compound Indexes

A compound index covers multiple fields together, like indexing both {status, createdDate}. This is perfect for queries filtering on both fields. Order matters: the index is organized first by status, then by createdDate within each status value.

Indexes on Nested Fields

Since documents can nest objects, you can index paths like address.city or author.name. The database treats the nested path as a single indexable field, letting you efficiently query deeply nested data without scanning entire documents.

When to Use Each Type

  • Single field: Queries filtering on one attribute
  • Compound: Queries using multiple fields together, or range queries on the second field after equality on the first
  • Nested: Queries targeting embedded objects

Key Takeaway: Indexing document fields—whether simple, compound, or nested—transforms slow full-collection scans into fast targeted lookups by creating efficient access paths to your data.