MongoDB Migrations in C#

2026, Oct 26    

A little while ago I wrote about the MongoDB decimal change that quietly broke our migration. A driver upgrade had left us with money stored as strings in some documents and as Decimal128 in others. Our migration hit the first string, failed, and then politely retried the same thing over and over again.

The data needed fixing, but so did the way we ran migrations. They were background jobs inside the API, with every instance having a go and nothing keeping a useful record of what had actually changed. I wanted to write them in C#, run each one safely, and be able to answer the question “what did it do?” afterwards.

Meet Kevsoft.MigrateMongo

Full disclosure: the migration tool in this post is one I wrote. I wanted migrations that are:

  • written in C# with the normal MongoDB driver;
  • run in a transaction when the cluster supports it;
  • guarded by a lock, so two runs can’t trip over each other;
  • checksummed, so nobody quietly edits one that’s already been applied;
  • able to tell you exactly what they did.

It’s called Kevsoft.MigrateMongo, and the getting started guide covers the setup in more detail.

Getting a migrations project running

Migrations live in a small console project that you own. You’ll need .NET 10 or later and MongoDB 5.0 or later. Transactions need a replica set or sharded cluster; for a local replica set, MongoDB Atlas Local is handy:

docker run -d --name mongo -p 27017:27017 mongodb/mongodb-atlas-local:8.0

From the root of your repository, install the local .NET tool and let it create the project:

dotnet new tool-manifest
dotnet tool install Kevsoft.MigrateMongo.Tool
dotnet migrate-mongo init --project src/MyApp.Migrations

If you already have a tool manifest, you can skip the first command. The generated migrate-mongo.yaml points to the project and reads the connection string from MONGODB_URL. Set the database name to shop:

project: src/MyApp.Migrations
mongodb:
  url: ${MONGODB_URL}
  databaseName: shop

For the local container, set the connection string in your shell:

export MONGODB_URL="mongodb://localhost:27017/?directConnection=true"

Now create a migration:

dotnet migrate-mongo create AddCustomerIdIndexToOrders

The generated file has a timestamp for its ID. Here’s a small example that creates an index; replace the generated class with this one, keeping the ID the tool generated rather than mine:

using Kevsoft.MigrateMongo;
using MongoDB.Bson;
using MongoDB.Driver;

namespace MyApp.Migrations.Migrations;

[Migration("20261022080000", "add-customer-id-index-to-orders", Transaction = TransactionMode.Never)]
public sealed class AddCustomerIdIndexToOrders : IMigration
{
    public Task UpAsync(MigrationContext context, CancellationToken cancellationToken) =>
        Orders(context).CreateIndexAsync(
            new CreateIndexModel<BsonDocument>(
                Builders<BsonDocument>.IndexKeys.Ascending("customerId"),
                new CreateIndexOptions { Name = "customerId_1" }),
            cancellationToken: cancellationToken);

    public Task DownAsync(MigrationContext context, CancellationToken cancellationToken) =>
        Orders(context).DropIndexAsync("customerId_1", cancellationToken: cancellationToken);

    private static TrackedCollection<BsonDocument> Orders(MigrationContext context) =>
        context.Track(context.Database.GetCollection<BsonDocument>("orders"));
}

UpAsync creates the index and DownAsync removes it. The tracked collection records both operations. Index builds on existing collections can’t run in a transaction, which is why this migration uses TransactionMode.Never. Use a fresh test database for this example: its rollback drops the named index.

Now you can see what’s pending, apply it, and inspect what happened:

dotnet migrate-mongo status
dotnet migrate-mongo up
dotnet migrate-mongo show <your-migration-id>

Use the ID from the generated file in place of <your-migration-id>. Run up again and the applied migration isn’t repeated. On a disposable database, dotnet migrate-mongo down rolls it back; up applies it again.

A backfill with something to say

An index is a nice small example, but I also wanted to know how much data a migration changed. Here’s an excerpt from the backfill in the decimal story, the one that fills in each order line’s LineTotal:

[Migration("20261022090000", "backfill-line-totals")]
public sealed class BackfillLineTotals : IMigration
{
    public async Task UpAsync(MigrationContext context, CancellationToken cancellationToken)
    {
        var orders = context.Track(context.Database.GetCollection<BsonDocument>("orders"), "backfilled");

        await orders.UpdateManyAsync(
            Builders<BsonDocument>.Filter.Exists("Lines.LineTotal", false),
            LineTotalFromPriceAndQuantity, // the $map pipeline from the decimal post
            cancellationToken: cancellationToken);

        var empty = await orders.Collection.CountDocumentsAsync(
            context.Session, Builders<BsonDocument>.Filter.Size("Lines", 0), cancellationToken: cancellationToken);
        context.Results.Set("emptyOrders", empty);
        if (empty > 0)
        {
            context.Results.Note($"{empty} orders have no lines.", NoteLevel.Warning);
        }
    }

    // DownAsync and the pipeline are omitted from this excerpt.
}

The decimal post shows the update pipeline and why the old string values need converting first. This excerpt isn’t a complete migration: a real DownAsync needs to be designed for the data, and not every backfill can safely be undone.

context.Track wraps the collection. The update runs exactly as it normally would, inside the migration’s transaction with the session passed for you, but it also gets written down:

  • what kind of operation it was;
  • its filter and update;
  • how many documents it matched and modified;
  • how long it took.

The "backfilled" label adds those counts to the migration’s results. context.Results holds anything else worth keeping, like a count or a warning.

Running that backfill looks like this:

$ dotnet migrate-mongo up
Built src/MyApp.Migrations/MyApp.Migrations.csproj (3.3s)
Runner: Kevsoft.MigrateMongo 1.0.0 · MongoDB.Driver 3.13.0 · .NET 10.0.14 · protocol 1
Acquired lock (run 05d63952bd8541e29d4890bdca002726).
▶ 20261022090000 backfill-line-totals
  warning: 3 orders have no lines.
✔ 20261022090000 backfill-line-totals   (0.21s, transaction)
    backfilled   matched 12480 · modified 12477 · upserted 0
    emptyOrders  3
    1 operation(s) recorded – migrate-mongo show 20261022090000
Applied 1 migration(s) in batch 1.

Look at those counts. They aren’t a log line somebody remembered to write. They’re what MongoDB reported back, and they’ve already caught something: 12,480 orders matched, but only 12,477 were modified. The missing three are the empty orders. Mapping over an empty array changes nothing, so MongoDB doesn’t count them as modified. It’s a harmless difference this time, but it’s exactly the kind of detail you’d never see if all you had was “migration complete”.

Behind the scenes the tool keeps three collections:

  • _migrations, with one document per migration, including its results and operations;
  • _migrations.history, an append-only log;
  • _migrations.lock, which only exists while a run is in progress. It’s what stops two deploys applying the same migration twice.

The best bit: every operation, written down

Logs are great while you’re watching, but they don’t necessarily stick around. The questions I actually get asked about a migration tend to come months later. What exactly did that change? How many orders did it touch? What did that index look like before we dropped it?

This is my favourite part of the tool. Everything a migration records is stored with it, on its document in _migrations and on its history entry, so the database itself remembers. Here’s an illustrative show result for the backfill:

$ dotnet migrate-mongo show 20261022
Runner: Kevsoft.MigrateMongo 1.0.0 · MongoDB.Driver 3.13.0 · .NET 10.0.14 · protocol 1
20261022090000 backfill-line-totals
  State     applied (batch 1, up, transaction)
  Applied   2026-10-26 09:14:44 by app@localhost (0.21s)
  Checksum  sha256:0c42cc28e360b5df3578c229212681dbf10437d22188167b6214023c32797a79
  Source    csharp MyApp.Migrations.Migrations.BackfillLineTotals
  Versions  tool migrate-mongo/1.0.0 (linux-x64; aot), library 1.0.0, driver 3.13.0
  Run       05d63952bd8541e29d4890bdca002726

Results
  backfilled   { matched: 12480, modified: 12477, upserted: 0 }
  emptyOrders  3

Notes
  09:14:43  warning  3 orders have no lines.

Operations
  1. updateMany orders [backfilled]  matched 12480 · modified 12477 · upserted 0  (0.18s)
       filter: { Lines.LineTotal: { $exists: false } }
       update: [{ $set: { Lines: { $map: { input: "$Lines", as: "line", in: { $mergeObjects: ["$$line", { LineTotal: { $multiply: ["$$line.UnitPrice", "$$line.Quantity"] } }] } } } } }]

History
 At                   ID              Name                  Event    Batch  Run       Host          Error  Results
 2026-10-26 09:14:44  20261022090000  backfill-line-totals  applied  1      05d63952  localhost           backfilled: matched 12480 · modified 12477 · upserted 0, em…

There’s a lot packed into that, so let me pick out what makes it so useful:

  • The counts are MongoDB’s, not yours. They come straight from the server’s result, so a migration that quietly modified nothing can’t hide behind a cheerful log line. modified 0 would be sitting right there, just like the three empty orders are here.
  • You get the statement that actually ran. The exact filter and update, which is the first thing you reach for when the numbers look odd. If your filters contain data you’d rather not keep, results.captureStatements: false turns statements off and keeps only the kinds, counts and timings.
  • Dropping an index records it first. A tracked DropIndexAsync saves the index’s full definition before dropping it, so a migration (or a rollback) that removes an index leaves you the recipe to put it back.
  • Failures keep what they recorded. A migration that fails keeps everything it recorded up to that point. If its transaction was aborted, the results are marked resultsCommitted: false and the log says (transaction aborted – changes not persisted), so you can tell what it tried from what actually stuck.
  • It’s all just documents. Results are stored as native BSON, so you can query them like anything else. Every migration that has ever touched the orders collection is one query away:

    db["_migrations"].find({ "operations.collection": "orders" }, { name: 1, results: 1 })
    

A few things to keep in mind

  • Track what you touch. Wrap collections with context.Track and record anything worth knowing later in context.Results.
  • Never edit a migration that’s been applied. The checksum will catch you, so write a new one instead.
  • Think about old code too. If the application is still running while a migration happens, make changes it can work with. Expand first, then remove old fields in a later release.
  • Allow out-of-order migrations (allowOutOfOrder: true) if pull requests can merge in a different order from when their migrations were created.

Wrapping up

Writing the migration is only half the story. I want to know what ran, whether it worked, and what it changed without going hunting through old logs. Keeping that information alongside the migration makes the next investigation a lot less exciting, in the best possible way.

How do you run your MongoDB migrations, and what do you keep around to tell you what they did? Let me know in the comments.