CLI tool to create and manage MongoDB indexes using code
Install the package globally or alternatively you can also use npx
npm install -g mondexHere is the list of mondex commands that you can use
pull— creates index configuration file by pulling existing indexes from your databaseplan— shows the indexes to be created or droppedapply— applies the changes from the configuration file (i.e. apply or drop indexes)
The list of options accepted by mondex are
Usage: mondex <command> [options]
Commands:
pull Creates index configuration from database
plan Shows the index changes to be applied to database
apply Applies the index changes from configuration to database
Options:
-V, --version output the version number
-h, --help display help for command
-f, --file <file> path to indexes file (defaults to indexes.json in current directory)
-i --uri <uri> connection string for MongoDB
-d, --db <database> database nameThe index configuration file is an array of objects with each object having two properties:
collection: Name of the collectionindexes: Array of indexes to be created
Index format is same as the one you would pass to db.collection.createIndex() in the mongo shell.
Given below is a sample JSON file representing sample index configuration:
[
{
"collection": "user_resource_progress",
"indexes": [
{ "resourceId": -1, "resourceType": -1, "userId": -1 },
{ "deletedAt": -1, "createdAt": -1 }
]
},
{
"collection": "user",
"indexes": [
{ "email": -1 },
{ "userType": -1, "createdAt": -1 },
{ "organizationId": -1, "userId": -1, "isActive": -1 }
]
}
]Once you have the JSON file ready, you can use the mondex to start managing your indexes.
Mondex supports special @ fields in index configuration to control index behavior:
| Field | Type | Description |
|---|---|---|
@isUnique |
boolean |
Creates a unique index |
@isSparse |
boolean |
Creates a sparse index |
@expireAfterSeconds |
number |
Creates a TTL index |
@partialFilterExpression |
object |
Creates a partial index |
[
{
"collection": "user",
"indexes": [
{ "email": -1, "@isUnique": true },
{ "userType": -1, "createdAt": -1 },
{ "organizationId": -1, "userId": -1, "isActive": -1 }
]
},
{
"collection": "activity_log",
"indexes": [
{ "createdAt": -1, "@expireAfterSeconds": 86400 }
]
},
{
"collection": "sessions",
"indexes": [
{ "token": 1, "@isUnique": true, "@isSparse": true },
{ "status": 1, "@partialFilterExpression": { "status": "active" } }
]
}
]If you change an index's options (e.g. add @isSparse to an existing index), plan and apply will detect the change and drop+recreate the index.
Show the indexes that will be created and dropped
mondex plan --uri mongodb://localhost:27017 --db mydb --file ./indexes.jsonApply the changes from index configuration
mondex apply --uri mongodb://localhost:27017 --db mydb --file ./indexes.jsonPull existing database indexes in the configuration file
mondex pull --uri mongodb://localhost:27017 --db mydb --file ./indexes.jsonMIT © Kamran Ahmed