mongrator
Lightweight MongoDB schema migration tool with synchronous and asynchronous PyMongo support.
Installation
pip install mongrator
Or with uv:
uv add mongrator
Quick start
# Create config and migrations directory
mongrator init
# Generate a new migration file
mongrator create add_users_email_index
# Check migration status
mongrator status
# Apply pending migrations
mongrator up
# Roll back the last migration
mongrator down
Configuration
mongrator init creates a mongrator.toml stub:
uri = "mongodb://localhost:27017"
database = "mydb"
migrations_dir = "migrations"
collection = "mongrator_migrations" # optional
Alternatively, configure via environment variables:
| Variable | Description | Required |
|---|---|---|
MONGRATOR_URI |
MongoDB connection URI | yes |
MONGRATOR_DB |
Database name | yes |
MONGRATOR_MIGRATIONS_DIR |
Path to migrations directory | no (default: migrations) |
MONGRATOR_COLLECTION |
Tracking collection name | no (default: mongrator_migrations) |
Writing migrations
Migration files are plain Python named {timestamp}_{slug}.py (e.g. 20260408_143022_add_users_email_index.py). Each file must define an up(db) function. A down(db) function is optional but enables rollback.
Using the ops helpers (recommended)
The ops helpers record their own inverses, so down() is generated automatically:
from mongrator import ops
def up(db):
return [
ops.create_index("users", {"email": 1}, unique=True),
ops.rename_field("users", "username", "handle"),
ops.add_field("users", "verified", default_value=False),
]
Using plain PyMongo
For complex logic, write directly against the db argument and define down() manually:
def up(db):
db["orders"].update_many(
{"status": {"$exists": False}},
{"$set": {"status": "pending"}},
)
def down(db):
db["orders"].update_many({}, {"$unset": {"status": ""}})
Available ops helpers
| Helper | Reversible | Description |
|---|---|---|
ops.create_index(collection, keys, **kwargs) |
yes | Create an index |
ops.drop_index(collection, index_name, keys=None, **kwargs) |
keys1 | Drop an index by name |
ops.rename_field(collection, old, new, filter=None) |
yes | Rename a field across documents |
ops.add_field(collection, field, default_value, filter=None) |
yes | Add a field with a default value |
CLI reference
mongrator init create migrations dir and mongrator.toml
mongrator create <name> generate a new migration file
mongrator status show applied/pending migrations
mongrator up [--target ID] apply pending migrations
mongrator up --async [--target ID] apply using async runner
mongrator down [--steps N] roll back N migrations (default: 1)
mongrator down --async [--steps N] roll back using async runner
mongrator validate verify checksums of applied migrations
mongrator --config PATH <command> use an alternate config file
Async usage
Pass --async to up or down to use the async runner (backed by pymongo.AsyncMongoClient):
mongrator up --async
To use the runners programmatically:
# Synchronous
from pathlib import Path
import pymongo
from mongrator.config import MigratorConfig
from mongrator.runner import SyncRunner
config = MigratorConfig(uri="mongodb://localhost:27017", database="mydb", migrations_dir=Path("migrations"))
runner = SyncRunner(pymongo.MongoClient(config.uri), config)
runner.up()
# Asynchronous
from pymongo import AsyncMongoClient
from mongrator.runner import AsyncRunner
runner = AsyncRunner(AsyncMongoClient(config.uri), config)
await runner.up()
Migration tracking
Applied migrations are recorded in the mongrator_migrations collection (configurable) within the target database. Each document stores:
_id— migration file stemapplied_at— UTC timestampchecksum— SHA-256 of the migration file at time of applicationdirection—"up"or"down"duration_ms— execution time in milliseconds
Running mongrator validate compares current file checksums against recorded values and reports any modifications.
-
Only reversible when
keysis provided. See writing migrations for details. ↩
Metadata
Release files for mongrator 0.4.3
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| mongrator-0.4.3.tar.gz | 18.0 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| mongrator-0.4.3-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 40.7 kB
Release files / mongrator-0.4.3.tar.gz
| Download URL | mongrator-0.4.3.tar.gz |
|---|---|
| Size | 18.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
81ebeffef450a03fe684308c0ad56af2a541aea4634cf8b31b7e74e7a0b0ec65
|
|
BLAKE2b-256 checksum How to use checksums |
c41d50531eeb313a40b262e2e8794ca02d8c9810f1212ac97263871bcd2cf429
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.13.13
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Jul 10, 2026.
Transparency logRelease files / mongrator-0.4.3-py3-none-any.whl
| Download URL | mongrator-0.4.3-py3-none-any.whl |
|---|---|
| Size | 22.7 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
78132c1bc36d185164eae1c39e79091c4a97a48b3e55396e3ccdb08220a679b2
|
|
BLAKE2b-256 checksum How to use checksums |
ef2c7bff01f3e0705213a266389b19780d42ddb4b8bc9b6054875b2a2878aae4
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.13.13
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Jul 10, 2026.
Transparency log