Working with Single-Field Indexes

1. Creating Single Field Index

FormEffect
createIndex({field: 1})Ascending B-tree
createIndex({field: -1})Descending (same for single-field)
Auto _idAlways exists

2. Creating Ascending Index

UseDetail
Sort ascIndex used directly
Range scan$gte, $lt traversal
EqualityO(log n) point lookup

3. Creating Descending Index

When to useReason
Single-fieldDirection doesn't matter (server can scan either way)
CompoundDirection matters for sort optimization

4. Listing Indexes

MethodOutput
getIndexes()Array of full index specs
getIndexKeys()Key patterns only
stats().indexSizesBytes per index

5. Dropping Index

FormEffect
dropIndex("name")By name
dropIndex({field: 1})By key pattern

6. Dropping All Indexes

FormNotes
dropIndexes()Drops all except _id
Use caseBulk re-index before refactor

7. Setting Unique Constraint

OptionEffect
unique: trueEnforce uniqueness
Null handlingMultiple nulls count as duplicates unless sparse/partial
Compound uniqueCombination must be unique

8. Setting Sparse Index

AspectDetail
sparse: trueOnly indexes docs with the field
vs PartialPartial is more flexible; sparse legacy form
Sort caveatSort may not use sparse index when missing fields exist

9. Setting Index Name

DefaultCustom
field_1{ name: "idx_email_unique" }
Max length127 bytes

10. Creating Background Index

VersionBehavior
≥ 4.2All index builds are hybrid (non-blocking); background option ignored
Replica setBuilds in parallel on each member
Resource useThrottles to avoid impacting ops

11. Using Index Hints

FormEffect
.hint("idx_email")Force index by name
.hint({email: 1})Force by key
.hint({$natural: 1})Force collection scan

12. Analyzing Index Usage

ToolOutput
$indexStats stagePer-index access counts
explain("executionStats")winningPlan + index used
Mongo Atlas Perf AdvisorIndex suggestions
db.users.aggregate([{ $indexStats: {} }]).toArray();