Use `db.collection.createIndex(keys, options)` in mongosh to create an index for a collection. `keys` names fields and their index direction (`1` ascending, `-1` descending); `options` sets additional properties. Choose fields that match the queries you need to support. section 7.2.1
Index a query field, then check its use
Run `db.movies.createIndex({ runtime: 1 })` to index movie runtimes. Use `db.movies.getIndexes()` to confirm the new `runtime_1` index alongside the automatic `_id_` index. Then run `db.movies.find({ runtime: 100 }).explain("executionStats")`; an `IXSCAN` on `runtime_1` shows that the query used it. section 7.2.1
Options adapt the index to different data needs:
- `partialFilterExpression` indexes only documents matching a filter, reducing storage and index maintenance costs. section 7.4.1
- `sparse: true` omits documents missing the indexed field; partial indexes offer broader functionality and are preferred. section 7.4.2
- `expireAfterSeconds` creates a single-field TTL index on a date field or array of dates, so documents expire automatically. section 7.4.3
db.getSiblingDB('sample_mflix').movies.createIndex(
{
year: 1,
type: 1,
"imdb.rating": 1
},
{
partialFilterExpression: { type: { $eq: "movie" } }
} // Creates a partial index on the movies collection
➥for documents where type is "movie"
)
This command combines a compound key with `partialFilterExpression`, indexing only movies whose `type` is `movie`. section 7.4.1
Expire dated records
Run `db.getSiblingDB('sample_analytics').transactions.createIndex({ date: 1 }, { expireAfterSeconds: 31536000 })` to expire transactions one year after their `date` value. A TTL value of `0` instead uses each indexed date as its expiration time. section 7.4.3
Plan index creation as an operational change: index builds take exclusive collection locks at their beginning and end, while reads and writes can interleave during the build. Explicit index creation is not permitted inside a transaction using a read concern other than `local`. section 7.8 section 8.5
