lilydocs
HTTP APIWebSocketConsumer
Data2 min read

MongoDB transactions and migrations

Manage MongoDB operations with explicit transaction decisions and versioned migration plans.

The application decides whether a MongoDB transaction commits or aborts. Do not assume the same scoped workflow behavior as PostgreSQL.

Prepare for transactions#

Set up the MongoDB connection. You need a deployment that supports transactions, such as a suitable replica set. Check support first with verify_transaction_capability().

Operation order#

  1. Create a configured context with DatabaseService::operation_context(token).
  2. Call begin_transaction(&operation).
  3. Select with_transaction(&transaction) on the context passed to operations.
  4. Run the domain operations with this context.
  5. Explicitly choose commit on success or abort on failure.

This sequence is an operation recipe. Your application's transaction wrapper must handle error precedence, the cleanup budget, and an uncertain commit outcome.

Cleanup after cancellation#

Reusing an already cancelled operation token for abort can immediately interrupt cleanup. Create a separate, time-bounded context for cleanup. If the commit outcome is uncertain, do not claim the data was definitely rolled back; apply your domain's retry/idempotency policy.

Versioned migrations#

The migration flow is MongoMigration::new(positive_version, name, steps) → MongoMigrationRunner::new(&database, plan) → apply(&operation).

MongoCollection index/unique attributes generate migration steps; they do not run DDL automatically during collection initialization. Apply migrations as a deliberate startup or deployment step.

The runner manages the plan with version/checksum validation and a distributed lease. Independent framework components can choose separate namespaces through for_component. Add a new version instead of silently changing an applied migration.

CrudService boundary#

CrudService derive generates DTO CRUD over a Mongo repository. It is not an HTTP controller macro or a shared CRUD engine for PostgreSQL. Its generated calls use detached Mongo operation contexts. Prefer explicit domain methods for flows requiring an HTTP deadline or a transaction.

Example coverage. Mongo APIs and derive contracts have been reviewed in the published source. The initial collection compilation predates the facade; current example validation is recorded separately on the testing page. The transaction/migration recipe on this page is not an application test validated against a live Mongo deployment.

Sources for this page v0.1.0

This guide is based on the reviewed framework commit.

QUICK START
Documentation
Source code