Working with Single-Field Indexes
1. Creating Single Field Index
| Form | Effect |
|---|---|
createIndex({field: 1}) | Ascending B-tree |
createIndex({field: -1}) | Descending (same for single-field) |
| Auto _id | Always exists |
2. Creating Ascending Index
| Use | Detail |
|---|---|
| Sort asc | Index used directly |
| Range scan | $gte, $lt traversal |
| Equality | O(log n) point lookup |
3. Creating Descending Index
| When to use | Reason |
|---|---|
| Single-field | Direction doesn't matter (server can scan either way) |
| Compound | Direction matters for sort optimization |
4. Listing Indexes
| Method | Output |
|---|---|
| getIndexes() | Array of full index specs |
| getIndexKeys() | Key patterns only |
| stats().indexSizes | Bytes per index |
5. Dropping Index
| Form | Effect |
|---|---|
dropIndex("name") | By name |
dropIndex({field: 1}) | By key pattern |
6. Dropping All Indexes
| Form | Notes |
|---|---|
| dropIndexes() | Drops all except _id |
| Use case | Bulk re-index before refactor |
7. Setting Unique Constraint
| Option | Effect |
|---|---|
| unique: true | Enforce uniqueness |
| Null handling | Multiple nulls count as duplicates unless sparse/partial |
| Compound unique | Combination must be unique |
8. Setting Sparse Index
| Aspect | Detail |
|---|---|
| sparse: true | Only indexes docs with the field |
| vs Partial | Partial is more flexible; sparse legacy form |
| Sort caveat | Sort may not use sparse index when missing fields exist |
9. Setting Index Name
| Default | Custom |
|---|---|
field_1 | { name: "idx_email_unique" } |
| Max length | 127 bytes |
10. Creating Background Index
| Version | Behavior |
|---|---|
| ≥ 4.2 | All index builds are hybrid (non-blocking); background option ignored |
| Replica set | Builds in parallel on each member |
| Resource use | Throttles to avoid impacting ops |
11. Using Index Hints
| Form | Effect |
|---|---|
.hint("idx_email") | Force index by name |
.hint({email: 1}) | Force by key |
.hint({$natural: 1}) | Force collection scan |
12. Analyzing Index Usage
| Tool | Output |
|---|---|
| $indexStats stage | Per-index access counts |
| explain("executionStats") | winningPlan + index used |
| Mongo Atlas Perf Advisor | Index suggestions |
db.users.aggregate([{ $indexStats: {} }]).toArray();