Skip to content
LESSON 21 / 50Beginnerindexing

Single-Field Indexes & Sort Directionality

Single-field indexes create a sorted B-Tree on one document attribute. Sort directionality (1 vs -1) does not matter for single-field queries because WiredTiger traverses B-Trees bidirectionally.

Interactive Engine Simulator

Index Traversal & IXSCAN vs COLLSCAN Execution Plan

Topic 21: Single-Field Indexes & Sort Directionality

Execution Stage
IXSCAN + FETCH
B-Tree leaf seek
Documents Examined
2
O(log N) lookup
Keys Examined
2
Index keys inspected
Query Latency
0.3 ms
WiredTiger execution time
Explain Plan Output Summary:
{
  "queryPlanner": {
    "winningPlan": {
      "stage": "FETCH",
      "inputStage": {
        "stage": "IXSCAN",
        "indexName": "role_1_country_1",
        "isMultiKey": false,
        "direction": "forward"
      }
    }
  },
  "executionStats": {
    "nReturned": 2,
    "executionTimeMillis": 1,
    "totalKeysExamined": 2,
    "totalDocsExamined": 2
  }
}

1. Formal Definition & Architecture Intent

A Single-Field Index creates an ordered B-Tree index structure on a single top-level or nested field in a collection. For single-field indexes, the index sort order (ascending 1 or descending -1) is arbitrary because the query planner can traverse the B-Tree in reverse direction with zero performance penalty.

2. Explain Like I'm 5 (Mental Model)

A single-field index is like a numbered contact list sorted A to Z. You can flip from front to back (A to Z) or back to front (Z to A) just as easily.

3. Real-World Architecture Example

Indexing email addresses for instant user lookup and sorting.

Sample BSON Documents:
Collection: db.users
{
  "_id": "u1",
  "email": "alice@cloud.io",
  "role": "admin"
}

An index on { email: 1 } satisfies both db.users.find().sort({ email: 1 }) and db.users.find().sort({ email: -1 }) with equal O(log N) speed.

4. MQL Implementation Steps

Step 1: Create an ascending index on a nested field
db.users.createIndex({ "profile.username": 1 }, { unique: true });
Unique constraint enforces that no two documents have identical values.
Step 2: Verify index usage with explain()
db.users.find({ "profile.username": "alice" }).explain("executionStats");
Winning plan shows IXSCAN on profile.username_1.

5. Critical Engineering Rules

Rule / ConstraintUnderlying Reason & Impact
Directionality NeutralityFor single field indexes, { age: 1 } and { age: -1 } are completely interchangeable.
The Default _id IndexMongoDB automatically creates a unique single-field index on _id; it cannot be dropped.

6. Deep Dive: B-Tree Forward vs Backward Iterator in WiredTiger

WiredTiger B-Tree leaf pages are linked by bidirectional pointers. A query requesting .sort({ age: -1 }) against an index created with { age: 1 } simply seeks to the highest key in the B-Tree and traverses backward using prev pointers. This symmetry does NOT apply to compound indexes with multiple fields!

// Drop redundant single-field index if compound index with same prefix exists:
db.users.dropIndex("email_1");
Production Warning: Every index incurs write overhead on insert/update/delete operations.

7. Architectural Trade-offs

Advantages
  • •Transforms O(N) collection scans (COLLSCAN) into O(log N) index seeks (IXSCAN)
  • •Satisfies both ascending and descending single-field sort operations natively
  • •Supports unique constraints to prevent duplicate data insertion
Disadvantages & Gotchas
  • •Each index consumes RAM in the working set and requires CPU/IO on every document write
  • •Cannot optimize multi-predicate queries filtering on independent columns

8. Technical Interview Questions

Q1: Does the sort direction (1 vs -1) matter when creating a single-field index?

No. Sort direction does not matter for single-field indexes because WiredTiger can traverse B-Tree leaf nodes in either direction with identical efficiency. Directionality only matters for compound indexes with multiple fields (e.g. { a: 1, b: -1 }).

9. Staff-Level Ready Answer

"A single-field index constructs a B-Tree on one attribute. Because WiredTiger can traverse B-Tree leaves bidirectionally, sort direction (1 vs -1) does not matter for single-field queries. Always verify index seeks via explain()."

10. Quick Knowledge Check

Which index will efficiently support the query: db.users.find().sort({ score: -1 })?