Tello.Mongo.Migration 0.1.0

dotnet add package Tello.Mongo.Migration --version 0.1.0
                    
NuGet\Install-Package Tello.Mongo.Migration -Version 0.1.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Tello.Mongo.Migration" Version="0.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Tello.Mongo.Migration" Version="0.1.0" />
                    
Directory.Packages.props
<PackageReference Include="Tello.Mongo.Migration" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Tello.Mongo.Migration --version 0.1.0
                    
#r "nuget: Tello.Mongo.Migration, 0.1.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Tello.Mongo.Migration@0.1.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Tello.Mongo.Migration&version=0.1.0
                    
Install as a Cake Addin
#tool nuget:?package=Tello.Mongo.Migration&version=0.1.0
                    
Install as a Cake Tool

Tello.Mongo.Migration

A lightweight, production-ready MongoDB migration framework for modern .NET applications.

Features

  • Forward & reversible migrations — implement IMongoMigration or IMongoReversibleMigration
  • Distributed locking — prevents concurrent migration runs across instances
  • Checksum validation — detects when applied migrations have been modified
  • Environment & tag filtering — run subsets of migrations per environment or tag
  • Dry-run planning — preview pending migrations without executing
  • Dependency injection — migrations support constructor injection

Installation

dotnet add package Tello.Mongo.Migration

Quick Start

1. Define a migration

public class CreateUsersIndex : IMongoMigration
{
    public string Id => "202402241200_CreateUsersIndex";
    public string Description => "Create unique index on users.email";

    public async Task UpAsync(IMongoDatabase database, CancellationToken ct)
    {
        var collection = database.GetCollection<BsonDocument>("users");
        var index = new CreateIndexModel<BsonDocument>(
            Builders<BsonDocument>.IndexKeys.Ascending("email"),
            new CreateIndexOptions { Unique = true });

        await collection.Indexes.CreateOneAsync(index, cancellationToken: ct);
    }
}

Migration IDs must match the format yyyyMMddHHmm_Description (12 digits, underscore, name). Migrations are executed in lexicographic order by ID.

2. Register in DI

services.AddMongoMigrations(opts =>
{
    opts.ConnectionString = "mongodb://localhost:27017";
    opts.DatabaseName = "MyDatabase";
    opts.AssembliesToScan = [typeof(CreateUsersIndex).Assembly];
});

Or with an existing IMongoClient:

services.AddMongoMigrations(opts =>
{
    opts.DatabaseName = "MyDatabase";
    opts.AssembliesToScan = [typeof(CreateUsersIndex).Assembly];
}, existingClient);

3. Run migrations

var runner = serviceProvider.GetRequiredService<IMongoMigrationRunner>();
await runner.RunAllAsync();

Reversible Migrations

Implement IMongoReversibleMigration and enable down migrations in options:

public class AddStatusField : IMongoReversibleMigration
{
    public string Id => "202402241300_AddStatusField";
    public string Description => "Add status field to orders";

    public async Task UpAsync(IMongoDatabase database, CancellationToken ct)
    {
        // forward migration
    }

    public async Task DownAsync(IMongoDatabase database, CancellationToken ct)
    {
        // rollback logic
    }
}
services.AddMongoMigrations(opts =>
{
    // ...
    opts.AllowDownMigrations = true;
});

Environment & Tag Filtering

Restrict migrations to specific environments or tag groups:

[MigrationEnvironment("production")]
[MigrationTag("schema")]
[MigrationTag("critical")]
public class ProductionOnlyMigration : IMongoMigration { /* ... */ }
services.AddMongoMigrations(opts =>
{
    // ...
    opts.EnvironmentName = "production";
    opts.TagFilter = ["schema"];
});
  • Migrations without [MigrationEnvironment] run in all environments.
  • Migrations without [MigrationTag] are excluded when a tag filter is active.

Runner API

IMongoMigrationRunner runner = /* from DI */;

// Execute all pending migrations
await runner.RunAllAsync();

// Execute up to a specific migration
await runner.RunToAsync("202402241300_AddStatusField");

// Dry-run plan (no execution, no lock)
MigrationPlan plan = await runner.GetPlanAsync();

// Validate only (no execution, no lock)
IReadOnlyList<string> warnings = await runner.ValidateAsync();

Configuration

Option Default Description
ConnectionString MongoDB connection string (optional if IMongoClient is provided)
DatabaseName Target database name (required)
AssembliesToScan Assemblies containing migrations (required)
TrackingCollectionName __migrations Collection storing applied migration records
LockCollectionName __migration_lock Collection used for distributed locking
LockTtl 5 minutes Lock time-to-live before expiry
LockAcquireTimeout 30 seconds Max wait time to acquire the lock
LockRetryDelay 2 seconds Delay between lock acquisition retries
EnvironmentName null Environment filter
TagFilter [] Tag filter list
AllowDownMigrations false Enable reversible migration rollback
EnableChecksumValidation true Validate checksums of applied migrations
FailOnChecksumChange true Throw on checksum mismatch
FailOnMissingMigration true Throw when applied migration is no longer discovered

Exceptions

Exception When
MigrationValidationException Duplicate IDs, invalid format, checksum mismatch, missing migrations
MigrationLockException Lock cannot be acquired within timeout
MigrationExecutionException A migration's UpAsync or DownAsync throws
Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.1.0 115 2/24/2026