The createIndexes command creates indexes for fields in a MongoDB collection, improving query performance by organizing indexed values for efficient retrieval. In mongosh, the related createIndex() helper accepts a key pattern and options such as uniqueness. section 7.2.1 section 7.8
A practical indexing workflow is:
- Choose the collection field and sort direction: 1 means ascending and -1 means descending. section 7.2.1
- Create the index, then use getIndexes() to confirm the automatically generated or specified index name and key pattern. section 7.2.1
- Validate query usage with explain("executionStats"), looking for an IXSCAN stage and reviewing examined keys and documents. section 7.2.1
- Account for operational choices such as partial, sparse, TTL, hidden, compound, multikey, text, wildcard, geospatial, and hashed indexes. section 7.8
Index and verify a movie-runtime query
Create an ascending index on movies.runtime with db.movies.createIndex({ "runtime": 1 }). Query the field, inspect the collection with getIndexes(), and run explain("executionStats") to verify that runtime_1 supplies the IXSCAN plan. The same index can support filtering and ascending sorting on runtime. section 7.2.1
db.movies.createIndex({"runtime": 1 })
Shows the copyable mongosh helper form for creating an ascending single-field index. section 7.2.1
Listing 7.3 Using the explain() method with the query
db.movies.find({ "runtime": 100 }).explain("executionStats")
{
explainVersion: '1',
queryPlanner: {
namespace: 'sample_mflix.movies',
indexFilterSet: false,
parsedQuery: { runtime: { '$eq': 100 } },
queryHash: 'ADC785B0',
planCacheKey: 'F015DF0A',
maxIndexedOrSolutionsReached: false,
maxIndexedAndSolutionsReached: false,
maxScansToExplodeReached: false,
winningPlan: {
stage: 'FETCH',
inputStage: {
stage: 'IXSCAN',
keyPattern: { runtime: 1 },
indexName: 'runtime_1',
isMultiKey: false,
multiKeyPaths: { runtime: [] },
isUnique: false,
isSparse: false,
isPartial: false,
indexVersion: 2,
direction: 'forward',
indexBounds: { runtime: [ '[100, 100]' ] }
}
},
rejectedPlans: []
},
executionStats: {
executionSuccess: true,
nReturned: 719,
executionTimeMillis: 3,
totalKeysExamined: 719,
totalDocsExamined: 719
Shows executionStats output for checking whether the query planner selected the created index. section 7.2.1
