Lightweight MongoDB schema migration tool
Project description
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. ↩
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file mongrator-0.4.1.tar.gz.
File metadata
- Download URL: mongrator-0.4.1.tar.gz
- Upload date:
- Size: 18.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.13
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a3e52bd6b323f1adcdddcd690c2d6876774588bd688bd0a0c06057bbc55f2efd
|
|
| MD5 |
deee8d1a087e625578cfc8e5d8527a98
|
|
| BLAKE2b-256 |
03f2a99a947c9fd86f35370b8fa1267a9bc2df2b5648821aec26c93bd8b2279d
|
Provenance
The following attestation bundles were made for mongrator-0.4.1.tar.gz:
Publisher:
publish.yml on sgerrand/pymongrator
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
mongrator-0.4.1.tar.gz -
Subject digest:
a3e52bd6b323f1adcdddcd690c2d6876774588bd688bd0a0c06057bbc55f2efd - Sigstore transparency entry: 1417550266
- Sigstore integration time:
-
Permalink:
sgerrand/pymongrator@37b905cc2325ec13b5cf735ebbf122a15afc734a -
Branch / Tag:
refs/tags/v0.4.1 - Owner: https://github.com/sgerrand
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@37b905cc2325ec13b5cf735ebbf122a15afc734a -
Trigger Event:
release
-
Statement type:
File details
Details for the file mongrator-0.4.1-py3-none-any.whl.
File metadata
- Download URL: mongrator-0.4.1-py3-none-any.whl
- Upload date:
- Size: 22.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.13
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
71aa0395c0f7a6c48bbf3af944f5bdaab6d549d26b19f0960e1aada6b3dc8e83
|
|
| MD5 |
dac798674778a90af67720aeab71e548
|
|
| BLAKE2b-256 |
fa940872d76425de3e4ee554220d5626679764e437cc1011988bd0754c50c8da
|
Provenance
The following attestation bundles were made for mongrator-0.4.1-py3-none-any.whl:
Publisher:
publish.yml on sgerrand/pymongrator
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
mongrator-0.4.1-py3-none-any.whl -
Subject digest:
71aa0395c0f7a6c48bbf3af944f5bdaab6d549d26b19f0960e1aada6b3dc8e83 - Sigstore transparency entry: 1417550289
- Sigstore integration time:
-
Permalink:
sgerrand/pymongrator@37b905cc2325ec13b5cf735ebbf122a15afc734a -
Branch / Tag:
refs/tags/v0.4.1 - Owner: https://github.com/sgerrand
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@37b905cc2325ec13b5cf735ebbf122a15afc734a -
Trigger Event:
release
-
Statement type: