### Run Migrations Source: https://github.com/adaskothebeast/adaskothebeast.mongodbmigrations/blob/main/README.md Basic example demonstrating how to initialize and run migrations using the MigrationEngineBuilder. ```APIDOC ## Run Migrations ```csharp using var engine = new MigrationEngineBuilder() .UseDatabase(connectionString, databaseName); var result = await engine .UseAssembly(Assembly.GetExecutingAssembly()) .UseSchemeValidation(false) .RunAsync(); ``` ``` -------------------------------- ### Full Migration Execution Example Source: https://github.com/adaskothebeast/adaskothebeast.mongodbmigrations/blob/main/README.md A comprehensive example showcasing various configuration options for running migrations, including SSH tunnel, TLS, schema validation, and progress handlers. ```APIDOC ### Full Example ```csharp using var engine = new MigrationEngineBuilder() .UseSshTunnel(sshServerAddress, user, privateKeyFileStream, mongoAddress, keyFilePassPhrase) // Optional: SSH tunnel .UseTls(cert) // Optional: TLS/SSL .UseDatabase(connectionString, databaseName); // Required var result = await engine .UseAssembly(assemblyWithMigrations) // Required .UseSchemeValidation(true, pathToCsproj) // Optional: Schema validation .UseProgressHandler(result => Console.WriteLine(result.MigrationName)) // Optional: Progress callback .UseBeforeMigration(migration => Console.WriteLine($"Starting: {migration.Name}")) // Optional: Before hook .UseAfterMigration((migration, success) => Console.WriteLine($"Completed: {migration.Name}")) // Optional: After hook .RunAsync(targetVersion, cancellationToken); // Execute (version and token are optional) ``` ``` -------------------------------- ### v2.x Migration Runner Source: https://github.com/adaskothebeast/adaskothebeast.mongodbmigrations/blob/main/README.md Example of how to run migrations using the v2.x MigrationEngine. ```csharp var result = new MigrationEngine() .UseDatabase(connectionString, databaseName) .UseAssembly(typeof(AddEmailIndex).Assembly) .UseSchemeValidation(false) .Run(); ``` -------------------------------- ### v3.x Migration Class Example Source: https://github.com/adaskothebeast/adaskothebeast.mongodbmigrations/blob/main/README.md Example of an asynchronous migration class for v3.x, using MigrationContext and async methods. ```csharp using System.Threading.Tasks; using AdaskoTheBeAsT.MongoDbMigrations.Abstractions; using MongoDB.Bson; using MongoDB.Driver; public class AddEmailIndex : IMigration { public Version Version => new Version(1, 0, 0); public string Name => "Add email index"; public async Task UpAsync(MigrationContext context) { var collection = context.Database.GetCollection("users"); var keys = Builders.IndexKeys.Ascending("email"); await collection.Indexes.CreateOneAsync( new CreateIndexModel(keys), cancellationToken: context.CancellationToken); } public async Task DownAsync(MigrationContext context) { var collection = context.Database.GetCollection("users"); await collection.Indexes.DropOneAsync("email_1", context.CancellationToken); } } ``` -------------------------------- ### v2.x Migration Class Example Source: https://github.com/adaskothebeast/adaskothebeast.mongodbmigrations/blob/main/README.md Example of a migration class for v2.x, implementing IMigration interface for Up and Down operations. ```csharp using MongoDBMigrations; using MongoDB.Bson; using MongoDB.Driver; public class AddEmailIndex : IMigration { public Version Version => new Version("1.0.0"); public string Name => "Add email index"; public void Up(IMongoDatabase database) { var collection = database.GetCollection("users"); var keys = Builders.IndexKeys.Ascending("email"); collection.Indexes.CreateOne(new CreateIndexModel(keys)); } public void Down(IMongoDatabase database) { var collection = database.GetCollection("users"); collection.Indexes.DropOne("email_1"); } } ``` -------------------------------- ### Install MongoDB Migrations Package Source: https://github.com/adaskothebeast/adaskothebeast.mongodbmigrations/blob/main/README.md Use this NuGet package manager command to install the main library into your application. ```powershell PM> Install-Package AdaskoTheBeAsT.MongoDbMigrations ``` -------------------------------- ### v3.x Migration Runner Source: https://github.com/adaskothebeast/adaskothebeast.mongodbmigrations/blob/main/README.md Example of how to run migrations using the v3.x MigrationEngineBuilder with asynchronous operations. ```csharp using var engine = new MigrationEngineBuilder() .UseDatabase(connectionString, databaseName); var result = await engine .UseAssembly(typeof(AddEmailIndex).Assembly) .UseSchemeValidation(false) .RunAsync(); ``` -------------------------------- ### Full Migration Engine Configuration Example Source: https://github.com/adaskothebeast/adaskothebeast.mongodbmigrations/blob/main/README.md Demonstrates comprehensive configuration of the MigrationEngine, including optional SSH tunnel, TLS/SSL, schema validation with a project path, and various hooks for migration events. ```csharp using var engine = new MigrationEngineBuilder() .UseSshTunnel(sshServerAddress, user, privateKeyFileStream, mongoAddress, keyFilePassPhrase) // Optional: SSH tunnel .UseTls(cert) // Optional: TLS/SSL .UseDatabase(connectionString, databaseName); // Required var result = await engine .UseAssembly(assemblyWithMigrations) // Required .UseSchemeValidation(true, pathToCsproj) // Optional: Schema validation .UseProgressHandler(result => Console.WriteLine(result.MigrationName)) // Optional: Progress callback .UseBeforeMigration(migration => Console.WriteLine($"Starting: {migration.Name}")) // Optional: Before hook .UseAfterMigration((migration, success) => Console.WriteLine($"Completed: {migration.Name}")) // Optional: After hook .RunAsync(targetVersion, cancellationToken); // Execute (version and token are optional) ``` -------------------------------- ### Generated Migration Registry Example Source: https://github.com/adaskothebeast/adaskothebeast.mongodbmigrations/blob/main/README.md This is an example of the MigrationRegistry class that is auto-generated at compile time by the source generator. ```csharp // Auto-generated at compile time in AdaskoTheBeAsT.MongoDbMigrations.Generated namespace [GeneratedMigrationRegistry] public static class MigrationRegistry { public static IReadOnlyList GetAllMigrations() => ... } ``` -------------------------------- ### Example Migration Class Source: https://github.com/adaskothebeast/adaskothebeast.mongodbmigrations/blob/main/README.md A typical migration class implementing IMigration, including UpAsync and DownAsync methods for database schema changes. ```csharp public class AddUserIndex : IMigration { public Version Version => new Version(1, 0, 0); public string Name => "Add index to users"; public async Task UpAsync(MigrationContext context) { var users = context.Database.GetCollection("users"); await users.Indexes.CreateOneAsync(...); } public async Task DownAsync(MigrationContext context) { var users = context.Database.GetCollection("users"); await users.Indexes.DropOneAsync(...); } } ``` -------------------------------- ### Create a Migration Source: https://github.com/adaskothebeast/adaskothebeast.mongodbmigrations/blob/main/README.md Example of how to create a migration class implementing the IMigration interface. This class defines the UpAsync and DownAsync methods for applying and reverting changes. ```APIDOC ## Create a Migration All migrations are async to match MongoDB driver patterns: ```csharp using System.Threading.Tasks; using AdaskoTheBeAsT.MongoDbMigrations.Abstractions; using MongoDB.Bson; using MongoDB.Driver; public class AddIndexToUsers : IMigration { public Version Version => new Version(1, 0, 0); public string Name => "Add index to users collection"; public async Task UpAsync(MigrationContext context) { var collection = context.Database.GetCollection("users"); var indexKeys = Builders.IndexKeys.Ascending("email"); await collection.Indexes.CreateOneAsync( new CreateIndexModel(indexKeys), cancellationToken: context.CancellationToken); } public async Task DownAsync(MigrationContext context) { var collection = context.Database.GetCollection("users"); await collection.Indexes.DropOneAsync("email_1", context.CancellationToken); } } ``` ``` -------------------------------- ### Migration Guide from v2.x to v3.x Source: https://github.com/adaskothebeast/adaskothebeast.mongodbmigrations/blob/main/README.md Information on breaking changes and necessary updates when migrating from version 2.x to version 3.x of the library, focusing on package structure and source generator architecture. ```APIDOC ## Migration Guide from v2.x to v3.x ### Breaking Changes #### 1. Package Structure Change (New in v3.x) Version 3.x splits the library into three packages: | v2.x | v3.x | |------|------| | `AdaskoTheBeAsT.MongoDbMigrations` (single package) | `AdaskoTheBeAsT.MongoDbMigrations.Abstractions` (interfaces) | | | `AdaskoTheBeAsT.MongoDbMigrations.SourceGenerators` (compile-time) | | | `AdaskoTheBeAsT.MongoDbMigrations` (runtime engine) | **Update your project references:** ```xml ``` #### 2. Source Generator Architecture (New in v3.x) Version 3.x introduces a source generator that replaces runtime Roslyn analysis. This means: - **Smaller deployments**: No more ~8MB Microsoft.CodeAnalysis dependency at runtime - **Faster startup**: Migration discovery is instant - **Compile-time validation**: Duplicate version numbers are caught during build The source generator automatically creates a `MigrationRegistry` class in your assembly. No action required - it works transparently. ``` -------------------------------- ### MigrationContext for Database Operations Source: https://context7.com/adaskothebeast/adaskothebeast.mongodbmigrations/llms.txt The MigrationContext provides access to the MongoDB database, session for transactions, and cancellation token. Use context.Database to get collections and context.CancellationToken for async operations. The context.Session can be used for transactional operations if available. ```csharp using System.Threading.Tasks; using AdaskoTheBeAsT.MongoDbMigrations.Abstractions; using MongoDB.Bson; using MongoDB.Driver; public class RenameFieldMigration : IMigration { public Version Version => new Version(1, 1, 0); public string Name => "Rename name field to firstName"; public async Task UpAsync(MigrationContext context) { // Access the database via context.Database var collection = context.Database.GetCollection("clients"); // Use context.CancellationToken for cancellation support await collection.UpdateManyAsync( FilterDefinition.Empty, Builders.Update.Rename("name", "firstName"), cancellationToken: context.CancellationToken); // context.Session is available for transaction support (may be null) if (context.Session != null) { // Use session for transactional operations await collection.InsertOneAsync( context.Session, new BsonDocument("audit", "field renamed"), cancellationToken: context.CancellationToken); } } public Task DownAsync(MigrationContext context) { var collection = context.Database.GetCollection("clients"); return collection.UpdateManyAsync( FilterDefinition.Empty, Builders.Update.Rename("firstName", "name"), cancellationToken: context.CancellationToken); } } ``` -------------------------------- ### Application NuGet Packages and Project Reference Source: https://github.com/adaskothebeast/adaskothebeast.mongodbmigrations/blob/main/README.md Reference the main package and your migrations project in your application startup project. ```xml ``` -------------------------------- ### MigrationEngine Initialization with MigrationEngineBuilder Source: https://github.com/adaskothebeast/adaskothebeast.mongodbmigrations/blob/main/README.md Shows the refactoring from directly instantiating MigrationEngine to using MigrationEngineBuilder. The MigrationEngineBuilder implements IDisposable and must be disposed after use. ```csharp var result = new MigrationEngine() .UseDatabase(...) .Run(); ``` ```csharp using var engine = new MigrationEngineBuilder() .UseDatabase(...); var result = await engine.RunAsync(); ``` -------------------------------- ### Configure Progress and Lifecycle Handlers for Migrations Source: https://context7.com/adaskothebeast/adaskothebeast.mongodbmigrations/llms.txt Configure progress callbacks and before/after migration hooks using `UseProgressHandler`, `UseBeforeMigration`, and `UseAfterMigration` to monitor and customize migration execution behavior. ```csharp using AdaskoTheBeAsT.MongoDbMigrations; using AdaskoTheBeAsT.MongoDbMigrations.Core.Contracts; using var engine = new MigrationEngineBuilder() .UseDatabase("mongodb://localhost:27017", "myDatabase"); var result = await engine .UseAssembly(typeof(MyMigrations).Assembly) .UseSchemeValidation(false) // Progress handler - called after each migration .UseProgressHandler(progress => { Console.WriteLine($"[{progress.CurrentNumber}/{progress.TotalCount}] " + $"{progress.MigrationName} -> {progress.TargetVersion}"); Console.WriteLine($" Server: {progress.ServerAddress}"); Console.WriteLine($" Database: {progress.DatabaseName}"); }) // Before migration hook .UseBeforeMigration(migration => { Console.WriteLine($"Starting migration: {migration.Name} (v{migration.Version})"); // Perform setup, logging, notifications, etc. }) // After migration hook .UseAfterMigration((migration, success) => { if (success) { Console.WriteLine($"Completed: {migration.Name}"); } else { Console.WriteLine($"FAILED: {migration.Name}"); // Send alert, log error, etc. } }) .RunAsync(); // Check interim steps in result foreach (var step in result.InterimSteps) { Console.WriteLine($"Applied: {step.MigrationName} at {step.TargetVersion}"); } ``` -------------------------------- ### Run Migrations with MigrationEngine Source: https://github.com/adaskothebeast/adaskothebeast.mongodbmigrations/blob/main/README.md Instantiate MigrationEngineBuilder, configure database connection and assembly containing migrations, then run migrations asynchronously. Schema validation can be disabled. ```csharp using var engine = new MigrationEngineBuilder() .UseDatabase(connectionString, databaseName); var result = await engine .UseAssembly(Assembly.GetExecutingAssembly()) .UseSchemeValidation(false) .RunAsync(); ``` -------------------------------- ### Configure MigrationEngineBuilder Source: https://context7.com/adaskothebeast/adaskothebeast.mongodbmigrations/llms.txt Use MigrationEngineBuilder to create and configure migration engines. Supports connection strings, existing clients, TLS, and SSH tunneling. ```csharp using System.Reflection; using System.Security.Cryptography.X509Certificates; using AdaskoTheBeAsT.MongoDbMigrations; using AdaskoTheBeAsT.MongoDbMigrations.Document; // Basic usage with connection string using var engine = new MigrationEngineBuilder() .UseDatabase("mongodb://localhost:27017", "myDatabase"); // With Azure CosmosDB emulation using var cosmosEngine = new MigrationEngineBuilder() .UseDatabase( "mongodb://cosmosdb-account.mongo.cosmos.azure.com:10255", "myDatabase", MongoEmulation.AzureCosmos); // With AWS DocumentDB using var awsEngine = new MigrationEngineBuilder() .UseDatabase(connectionString, "myDatabase", MongoEmulation.AwsDocument); // With existing MongoClient (engine will NOT dispose the client) var existingClient = new MongoClient("mongodb://localhost:27017"); using var engineWithClient = new MigrationEngineBuilder() .UseDatabase(existingClient, "myDatabase"); // With TLS/SSL certificate var certificate = new X509Certificate2("client.pfx", "password"); using var tlsEngine = new MigrationEngineBuilder() .UseTls(certificate) .UseDatabase("mongodb://secure-host:27017", "myDatabase"); // With SSH tunnel (password authentication) using var sshEngine = new MigrationEngineBuilder() .UseSshTunnel( new ServerAddressConfig("ssh-server.com", 22), "sshUser", "sshPassword", new ServerAddressConfig("mongo-host", 27017)) .UseDatabase("mongodb://localhost:27017", "myDatabase"); // With SSH tunnel (private key authentication) using var keyStream = File.OpenRead("private_key"); using var sshKeyEngine = new MigrationEngineBuilder() .UseSshTunnel( new ServerAddressConfig("ssh-server.com", 22), "sshUser", keyStream, new ServerAddressConfig("mongo-host", 27017), "keyPassphrase") .UseDatabase("mongodb://localhost:27017", "myDatabase"); ``` -------------------------------- ### Migration Interface: Up and Down Methods Source: https://github.com/adaskothebeast/adaskothebeast.mongodbmigrations/blob/main/README.md Shows the evolution of the IMigration interface from synchronous methods accepting IMongoDatabase to asynchronous methods accepting MigrationContext. The MigrationContext provides access to the database, session, and cancellation token. ```csharp public class MyMigration : IMigration { public Version Version => new Version(1, 0, 0); public string Name => "My migration"; public void Up(IMongoDatabase database) { database.GetCollection("users").InsertOne(...); } public void Down(IMongoDatabase database) { database.GetCollection("users").DeleteOne(...); } } ``` ```csharp public class MyMigration : IMigration { public Version Version => new Version(1, 0, 0); public string Name => "My migration"; public async Task UpAsync(MigrationContext context) { await context.Database.GetCollection("users") .InsertOneAsync(..., cancellationToken: context.CancellationToken); // Also available: context.Session (for transactions) } public async Task DownAsync(MigrationContext context) { await context.Database.GetCollection("users") .DeleteOneAsync(..., cancellationToken: context.CancellationToken); } } ``` -------------------------------- ### Async API Usage in MigrationEngine Source: https://github.com/adaskothebeast/adaskothebeast.mongodbmigrations/blob/main/README.md Illustrates the change from synchronous Run() to asynchronous RunAsync() in MigrationEngine. Ensure to use await for asynchronous operations. ```csharp var result = new MigrationEngine() .UseDatabase(connectionString, databaseName) .UseAssembly(assembly) .UseSchemeValidation(false) .Run(targetVersion); ``` ```csharp var result = await new MigrationEngineBuilder() .UseDatabase(connectionString, databaseName) .UseAssembly(assembly) .UseSchemeValidation(false) .RunAsync(targetVersion); ``` -------------------------------- ### Simulate Migration Execution with Dry Run Mode Source: https://context7.com/adaskothebeast/adaskothebeast.mongodbmigrations/llms.txt Use `UseDryRun(true)` to simulate migration execution without applying changes. This is useful for testing and validation before actual deployment. Set `UseDryRun(false)` for actual execution. ```csharp using AdaskoTheBeAsT.MongoDbMigrations; using var engine = new MigrationEngineBuilder() .UseDatabase("mongodb://localhost:27017", "myDatabase"); // Enable dry run mode var dryRunResult = await engine .UseAssembly(typeof(MyMigrations).Assembly) .UseDryRun(true) // No actual changes applied .RunAsync(); Console.WriteLine($"Is Dry Run: {dryRunResult.IsDryRun}"); // true Console.WriteLine($"Would migrate to: {dryRunResult.CurrentVersion}"); Console.WriteLine($"Steps that would run: {dryRunResult.InterimSteps.Count}"); foreach (var step in dryRunResult.InterimSteps) { Console.WriteLine($" - {step.MigrationName} -> {step.TargetVersion}"); } // Disable dry run for actual execution var actualResult = await engine .UseAssembly(typeof(MyMigrations).Assembly) .UseDryRun(false) .RunAsync(); ``` -------------------------------- ### Implement IMigration Interface Source: https://context7.com/adaskothebeast/adaskothebeast.mongodbmigrations/llms.txt Implement the IMigration interface to define a database migration. Specify version, name, and implement UpAsync/DownAsync methods for forward and backward migration logic. Ensure correct usage of MigrationContext for database operations and cancellation tokens. ```csharp using System.Threading.Tasks; using AdaskoTheBeAsT.MongoDbMigrations.Abstractions; using MongoDB.Bson; using MongoDB.Driver; public class AddEmailIndex : IMigration { // Semantic version in format MAJOR.MINOR.REVISION public Version Version => new Version(1, 0, 0); // Descriptive name for the migration public string Name => "Add unique index to users email field"; public async Task UpAsync(MigrationContext context) { var collection = context.Database.GetCollection("users"); var indexKeys = Builders.IndexKeys.Ascending("email"); var indexOptions = new CreateIndexOptions { Unique = true }; await collection.Indexes.CreateOneAsync( new CreateIndexModel(indexKeys, indexOptions), cancellationToken: context.CancellationToken); } public async Task DownAsync(MigrationContext context) { var collection = context.Database.GetCollection("users"); await collection.Indexes.DropOneAsync("email_1", context.CancellationToken); } } ``` -------------------------------- ### Execute Migrations with RunAsync Source: https://context7.com/adaskothebeast/adaskothebeast.mongodbmigrations/llms.txt The RunAsync method executes migrations up to the newest available version or a specified target version. Use UseAssembly or UseAssemblyOfType for migration discovery. Scheme validation can be disabled. ```csharp using System.Reflection; using AdaskoTheBeAsT.MongoDbMigrations; using AdaskoTheBeAsT.MongoDbMigrations.Abstractions; // Run all migrations to latest version using var engine = new MigrationEngineBuilder() .UseDatabase("mongodb://localhost:27017", "myDatabase"); var result = await engine .UseAssembly(Assembly.GetExecutingAssembly()) .UseSchemeValidation(false) .RunAsync(); Console.WriteLine($"Success: {result.Success}"); Console.WriteLine($"Current Version: {result.CurrentVersion}"); Console.WriteLine($"Server: {result.ServerAddress}"); Console.WriteLine($"Database: {result.DatabaseName}"); // Run to specific target version var targetResult = await engine .UseAssembly(Assembly.GetExecutingAssembly()) .RunAsync(new Version(1, 2, 0)); // Run with cancellation token using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(5)); var cancelableResult = await engine .UseAssembly(typeof(MyMigration).Assembly) .RunAsync(cts.Token); // Using UseAssemblyOfType for migration discovery var typeResult = await engine .UseAssemblyOfType() .RunAsync(); // Or with non-generic version var typeResult2 = await engine .UseAssemblyOfType(typeof(AddEmailIndex)) .RunAsync(); ``` -------------------------------- ### Migrations Project NuGet Packages Source: https://github.com/adaskothebeast/adaskothebeast.mongodbmigrations/blob/main/README.md Reference these packages in your class library project containing migration classes. ```xml ``` -------------------------------- ### Migration Engine Configuration Methods Source: https://github.com/adaskothebeast/adaskothebeast.mongodbmigrations/blob/main/README.md Reference for the configuration methods available in the MigrationEngineBuilder to customize migration execution. ```APIDOC ## API Reference ### Configuration Methods | Step | Methods | Description | |:-----|:--------|:------------| | 0 | `new MigrationEngineBuilder()` | Create engine builder instance | | 1 | `UseSshTunnel(...)`, `UseTls(...)`, `UseDatabase(...)` | Database connection | | 2 | `UseAssemblyOfType(...)`, `UseAssemblyOfType()`, `UseAssembly(...)` | Migration classes location | | 3 | `UseSchemeValidation(...)` | Schema validation | | 4 | `UseProgressHandler(...)`, `UseDryRun(...)`, `UseBeforeMigration(...)`, `UseAfterMigration(...)` | Handling features | | 5 | `RunAsync()`, `RunAsync(version)`, `RollbackAsync(steps)` | Execution | ``` -------------------------------- ### Create Compound Index Migration in C# Source: https://context7.com/adaskothebeast/adaskothebeast.mongodbmigrations/llms.txt This migration creates a compound index on 'email' (ascending) and 'createdAt' (descending) for the 'users' collection. The index is named 'email_createdAt_idx' and runs in the background. ```csharp using System.Threading.Tasks; using AdaskoTheBeAsT.MongoDbMigrations.Abstractions; using MongoDB.Bson; using MongoDB.Driver; // Migration 3: Create compound index public class AddCompoundIndex : IMigration { public Version Version => new Version(1, 2, 0); public string Name => "Add compound index on email and createdAt"; public async Task UpAsync(MigrationContext context) { var collection = context.Database.GetCollection("users"); var indexKeys = Builders.IndexKeys .Ascending("email") .Descending("createdAt"); var indexOptions = new CreateIndexOptions { Name = "email_createdAt_idx", Background = true }; await collection.Indexes.CreateOneAsync( new CreateIndexModel(indexKeys, indexOptions), cancellationToken: context.CancellationToken); } public async Task DownAsync(MigrationContext context) { var collection = context.Database.GetCollection("users"); await collection.Indexes.DropOneAsync( "email_createdAt_idx", context.CancellationToken); } } ``` -------------------------------- ### Create a MongoDB Migration Source: https://github.com/adaskothebeast/adaskothebeast.mongodbmigrations/blob/main/README.md Implement the IMigration interface to define UpAsync and DownAsync methods for schema changes. Ensure migrations are async to match MongoDB driver patterns. ```csharp using System.Threading.Tasks; using AdaskoTheBeAsT.MongoDbMigrations.Abstractions; using MongoDB.Bson; using MongoDB.Driver; public class AddIndexToUsers : IMigration { public Version Version => new Version(1, 0, 0); public string Name => "Add index to users collection"; public async Task UpAsync(MigrationContext context) { var collection = context.Database.GetCollection("users"); var indexKeys = Builders.IndexKeys.Ascending("email"); await collection.Indexes.CreateOneAsync( new CreateIndexModel(indexKeys), cancellationToken: context.CancellationToken); } public async Task DownAsync(MigrationContext context) { var collection = context.Database.GetCollection("users"); await collection.Indexes.DropOneAsync("email_1", context.CancellationToken); } } ``` -------------------------------- ### Transaction Support Configuration Source: https://github.com/adaskothebeast/adaskothebeast.mongodbmigrations/blob/main/README.md Enables transaction support for migration batches using the UseTransaction() method. ```csharp using var engine = new MigrationEngineBuilder() .UseDatabase(connectionString, databaseName) .UseTransaction(); var result = await engine .UseAssembly(assembly) .RunAsync(); ``` -------------------------------- ### Dry Run Mode Configuration Source: https://github.com/adaskothebeast/adaskothebeast.mongodbmigrations/blob/main/README.md Configures the MigrationEngineBuilder to run migrations in dry run mode using UseDryRun(true). ```csharp using var engine = new MigrationEngineBuilder() .UseDatabase(connectionString, databaseName); var result = await engine .UseAssembly(assembly) .UseDryRun(true) .RunAsync(targetVersion); // result.IsDryRun will be true // No changes are applied to the database ``` -------------------------------- ### CI/CD Integration Aliases Source: https://github.com/adaskothebeast/adaskothebeast.mongodbmigrations/blob/main/README.md Sets aliases for mongodump and mongorestore commands for use in CI/CD pipelines. ```powershell Set-Alias mongodump Set-Alias mongorestore ``` -------------------------------- ### Version Struct for Semantic Versioning Source: https://context7.com/adaskothebeast/adaskothebeast.mongodbmigrations/llms.txt The Version struct represents semantic versioning (MAJOR.MINOR.REVISION). It supports creation from integers or strings, comparison operators, implicit string conversion, and provides a Zero() method for the base version. Use CompareTo for sorting. ```csharp using AdaskoTheBeAsT.MongoDbMigrations.Abstractions; // Create version from integers var v1 = new Version(1, 0, 0); var v2 = new Version(1, 2, 3); // Create version from string var v3 = new Version("2.0.0"); // Implicit conversion from string Version v4 = "3.1.0"; // Comparison operators bool isNewer = v2 > v1; // true bool isEqual = v1 == new Version(1, 0, 0); // true bool isOlder = v1 < v2; // true // Zero version for rollback to beginning Version zero = Version.Zero(); // 0.0.0 // Convert to string string versionString = v2.ToString(); // "1.2.3" // CompareTo for sorting int comparison = v2.CompareTo(v1); // 1 (v2 > v1) ``` -------------------------------- ### Database State Checker Source: https://github.com/adaskothebeast/adaskothebeast.mongodbmigrations/blob/main/README.md Utility methods for checking the current state of the database regarding migrations and throwing exceptions if outdated. ```APIDOC ### Database State Checker ```csharp // Check if database needs migrations bool isOutdated = MongoDatabaseStateChecker.IsDatabaseOutdated( connectionString, databaseName, migrationAssembly, MongoEmulation.None); // Throw exception if outdated MongoDatabaseStateChecker.ThrowIfDatabaseOutdated( connectionString, databaseName, migrationAssembly); ``` ``` -------------------------------- ### Update Project References for v3.x Source: https://github.com/adaskothebeast/adaskothebeast.mongodbmigrations/blob/main/README.md Update NuGet package references in your project files to migrate from v2.x to v3.x of the MongoDB Migrations library. Separate packages are used for abstractions, source generators, and the runtime engine. ```xml ``` -------------------------------- ### Azure CosmosDB Support Configuration Source: https://github.com/adaskothebeast/adaskothebeast.mongodbmigrations/blob/main/README.md Configures the MigrationEngineBuilder to use Azure CosmosDB (MongoDB API) with MongoEmulation.AzureCosmos option. ```csharp using var engine = new MigrationEngineBuilder() .UseDatabase(connectionString, databaseName, MongoEmulation.AzureCosmos); var result = await engine .UseAssembly(assembly) .RunAsync(); ``` -------------------------------- ### Version Class Location Update Source: https://github.com/adaskothebeast/adaskothebeast.mongodbmigrations/blob/main/README.md Highlights the change in the location of the Version class, which has moved to the Abstractions package. Consider using a qualified name to avoid conflicts with System.Version. ```csharp using MongoDBMigrations; // Version was in main namespace ``` ```csharp using Version = AdaskoTheBeAsT.MongoDbMigrations.Abstractions.Version; // Or use fully qualified name to avoid conflict with System.Version ``` -------------------------------- ### Configure MongoEmulation for Different Databases Source: https://context7.com/adaskothebeast/adaskothebeast.mongodbmigrations/llms.txt Specify the database type using the MongoEmulation enum when building the MigrationEngine. This ensures compatibility with Azure CosmosDB and AWS DocumentDB. ```csharp using AdaskoTheBeAsT.MongoDbMigrations; using AdaskoTheBeAsT.MongoDbMigrations.Document; // Standard MongoDB (default) using var mongoEngine = new MigrationEngineBuilder() .UseDatabase( "mongodb://localhost:27017", "myDatabase", MongoEmulation.None); // Default value // Azure CosmosDB with MongoDB API using var cosmosEngine = new MigrationEngineBuilder() .UseDatabase( "mongodb://account.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb", "myDatabase", MongoEmulation.AzureCosmos); // AWS DocumentDB using var documentDbEngine = new MigrationEngineBuilder() .UseDatabase( "mongodb://docdb-cluster.cluster-xxxxx.us-east-1.docdb.amazonaws.com:27017/?tls=true", "myDatabase", MongoEmulation.AwsDocument); // Also works with state checker bool isOutdated = MongoDatabaseStateChecker.IsDatabaseOutdated( connectionString, databaseName, assembly, MongoEmulation.AzureCosmos); ``` -------------------------------- ### Rollback Migrations with RollbackAsync Source: https://context7.com/adaskothebeast/adaskothebeast.mongodbmigrations/llms.txt The RollbackAsync method rolls back the database by a specified number of migration steps. It executes the DownAsync methods of applied migrations in reverse order. Can rollback to version zero. ```csharp using AdaskoTheBeAsT.MongoDbMigrations; using var engine = new MigrationEngineBuilder() .UseDatabase("mongodb://localhost:27017", "myDatabase"); // Rollback 1 migration step var rollback1 = await engine .UseAssembly(typeof(MyMigrations).Assembly) .RollbackAsync(1); Console.WriteLine($"Rolled back to: {rollback1.CurrentVersion}"); // Rollback 3 migration steps var rollback3 = await engine .UseAssembly(typeof(MyMigrations).Assembly) .RollbackAsync(3); // Rollback with cancellation token using var cts = new CancellationTokenSource(); var rollbackCancelable = await engine .UseAssembly(typeof(MyMigrations).Assembly) .RollbackAsync(2, cts.Token); // Rollback to version zero (all migrations) var rollbackAll = await engine .UseAssembly(typeof(MyMigrations).Assembly) .RunAsync(Version.Zero()); ``` -------------------------------- ### Check Database Migration Status Source: https://github.com/adaskothebeast/adaskothebeast.mongodbmigrations/blob/main/README.md Utilize MongoDatabaseStateChecker to determine if the database requires migrations or to throw an exception if it's outdated. Requires migration assembly information. ```csharp // Check if database needs migrations bool isOutdated = MongoDatabaseStateChecker.IsDatabaseOutdated( connectionString, databaseName, migrationAssembly, MongoEmulation.None); // Throw exception if outdated MongoDatabaseStateChecker.ThrowIfDatabaseOutdated( connectionString, databaseName, migrationAssembly); ``` -------------------------------- ### Enable Transaction Support for Atomic Migration Batches Source: https://context7.com/adaskothebeast/adaskothebeast.mongodbmigrations/llms.txt Use `UseTransaction()` to enable transaction support for atomic migration batches. This requires MongoDB 4.0+ with replica set or sharded cluster configuration. Within your migration, use `context.Session` for transactional operations. ```csharp using AdaskoTheBeAsT.MongoDbMigrations; // Enable transaction support using var engine = new MigrationEngineBuilder() .UseDatabase("mongodb://localhost:27017/?replicaSet=rs0", "myDatabase"); var result = await engine .UseTransaction() // Enable transactions .UseAssembly(typeof(MyMigrations).Assembly) .UseSchemeValidation(false) .RunAsync(); // In your migration, use context.Session for transactional operations public class TransactionalMigration : IMigration { public Version Version => new Version(2, 0, 0); public string Name => "Transactional data migration"; public async Task UpAsync(MigrationContext context) { var users = context.Database.GetCollection("users"); var audit = context.Database.GetCollection("audit"); // Both operations are part of the same transaction await users.InsertOneAsync( context.Session, // Pass session for transaction new BsonDocument("name", "John"), cancellationToken: context.CancellationToken); await audit.InsertOneAsync( context.Session, new BsonDocument("action", "user_created"), cancellationToken: context.CancellationToken); } public async Task DownAsync(MigrationContext context) { var users = context.Database.GetCollection("users"); var audit = context.Database.GetCollection("audit"); await users.DeleteOneAsync( context.Session, new BsonDocument("name", "John"), cancellationToken: context.CancellationToken); await audit.DeleteOneAsync( context.Session, new BsonDocument("action", "user_created"), cancellationToken: context.CancellationToken); } } ``` -------------------------------- ### Rollback Migration Steps Source: https://github.com/adaskothebeast/adaskothebeast.mongodbmigrations/blob/main/README.md Rolls back a specified number of migration steps using the RollbackAsync() method. ```csharp using var engine = new MigrationEngineBuilder() .UseDatabase(connectionString, databaseName); // Rollback 2 migration steps var result = await engine .UseAssembly(assembly) .RollbackAsync(2); ``` -------------------------------- ### Namespace Changes in MongoDB Migrations Source: https://github.com/adaskothebeast/adaskothebeast.mongodbmigrations/blob/main/README.md Demonstrates the updated using directives required for v3.x of the MongoDB Migrations library. The primary namespace has changed from MongoDBMigrations to AdaskoTheBeAsT.MongoDbMigrations. ```csharp using MongoDBMigrations; ``` ```csharp using AdaskoTheBeAsT.MongoDbMigrations; using AdaskoTheBeAsT.MongoDbMigrations.Abstractions; ``` -------------------------------- ### Check Database Migration Status with MongoDatabaseStateChecker Source: https://context7.com/adaskothebeast/adaskothebeast.mongodbmigrations/llms.txt Utilize the MongoDatabaseStateChecker to determine if a database requires migrations without executing them. This is useful for application startup validation. It supports standard MongoDB and Azure CosmosDB. ```csharp using System.Reflection; using AdaskoTheBeAsT.MongoDbMigrations; using AdaskoTheBeAsT.MongoDbMigrations.Document; var connectionString = "mongodb://localhost:27017"; var databaseName = "myDatabase"; var migrationsAssembly = typeof(MyMigrations).Assembly; // Check if database is outdated bool isOutdated = MongoDatabaseStateChecker.IsDatabaseOutdated( connectionString, databaseName, migrationsAssembly, MongoEmulation.None); if (isOutdated) { Console.WriteLine("Database needs migrations!"); // Run migrations or alert admin } // Throw exception if outdated (useful for startup validation) try { MongoDatabaseStateChecker.ThrowIfDatabaseOutdated( connectionString, databaseName, migrationsAssembly); Console.WriteLine("Database is up to date"); } catch (DatabaseOutdatedException ex) { Console.WriteLine($"Database version: {ex.CurrentVersion}"); Console.WriteLine($"Required version: {ex.RequiredVersion}"); Environment.Exit(1); } // For Azure CosmosDB bool isCosmosOutdated = MongoDatabaseStateChecker.IsDatabaseOutdated( connectionString, databaseName, migrationsAssembly, MongoEmulation.AzureCosmos); ``` -------------------------------- ### Enable Schema Validation in Migration Engine Source: https://context7.com/adaskothebeast/adaskothebeast.mongodbmigrations/llms.txt Configure the MigrationEngineBuilder to validate that referenced collections exist in the database before executing migrations. This can be done with default or custom specification collection names. ```csharp using AdaskoTheBeAsT.MongoDbMigrations; using var engine = new MigrationEngineBuilder() .UseDatabase("mongodb://localhost:27017", "myDatabase"); // Enable schema validation var result = await engine .UseAssembly(typeof(MyMigrations).Assembly) .UseSchemeValidation(true) // Validate collections exist .RunAsync(); // With custom specification collection name var customResult = await engine .UseAssembly(typeof(MyMigrations).Assembly) .UseSchemeValidation(true) .UseCustomSpecificationCollectionName("_custom_migrations") // Default is "_migrations" .RunAsync(); ``` -------------------------------- ### Convert Field Data Type Migration in C# Source: https://context7.com/adaskothebeast/adaskothebeast.mongodbmigrations/llms.txt This migration converts a field's data type. `UpAsync` converts 'age' from int to string, and `DownAsync` converts it back to int. It iterates through documents to perform the update. ```csharp using System.Threading.Tasks; using AdaskoTheBeAsT.MongoDbMigrations.Abstractions; using MongoDB.Bson; using MongoDB.Driver; // Migration 2: Convert field data type public class ConvertAgeToString : IMigration { public Version Version => new Version(1, 1, 0); public string Name => "Convert age from int to string"; public async Task UpAsync(MigrationContext context) { var collection = context.Database.GetCollection("clients"); using var cursor = await collection.FindAsync( FilterDefinition.Empty, cancellationToken: context.CancellationToken); var documents = await cursor.ToListAsync(context.CancellationToken); foreach (var doc in documents) { await collection.UpdateOneAsync( new BsonDocument("_id", doc["_id"]), Builders.Update.Set("age", doc["age"].ToString()), cancellationToken: context.CancellationToken); } } public async Task DownAsync(MigrationContext context) { var collection = context.Database.GetCollection("clients"); using var cursor = await collection.FindAsync( FilterDefinition.Empty, cancellationToken: context.CancellationToken); var documents = await cursor.ToListAsync(context.CancellationToken); foreach (var doc in documents) { await collection.UpdateOneAsync( new BsonDocument("_id", doc["_id"]), Builders.Update.Set("age", doc["age"].ToInt32()), cancellationToken: context.CancellationToken); } } } ``` -------------------------------- ### Ignore Migration with [IgnoreMigration] Attribute Source: https://context7.com/adaskothebeast/adaskothebeast.mongodbmigrations/llms.txt Use the [IgnoreMigration] attribute to prevent a migration class from being discovered and executed. This is helpful for temporary or test migrations. ```csharp using AdaskoTheBeAsT.MongoDbMigrations.Abstractions; using MongoDB.Bson; using MongoDB.Driver; // This migration will be ignored during discovery [IgnoreMigration] public class TestMigration : IMigration { public Version Version => new Version(99, 0, 0); public string Name => "Test migration - ignored in production"; public async Task UpAsync(MigrationContext context) { var collection = context.Database.GetCollection("test"); await collection.InsertOneAsync( new BsonDocument("test", true), cancellationToken: context.CancellationToken); } public async Task DownAsync(MigrationContext context) { var collection = context.Database.GetCollection("test"); await collection.DeleteOneAsync( new BsonDocument("test", true), cancellationToken: context.CancellationToken); } } // This migration WILL be discovered and run public class ProductionMigration : IMigration { public Version Version => new Version(1, 0, 0); public string Name => "Production migration"; public Task UpAsync(MigrationContext context) => Task.CompletedTask; public Task DownAsync(MigrationContext context) => Task.CompletedTask; } ``` -------------------------------- ### Rename Field Migration in C# Source: https://context7.com/adaskothebeast/adaskothebeast.mongodbmigrations/llms.txt Use this migration to rename a field in a MongoDB collection. The `UpAsync` method renames 'name' to 'firstName', and `DownAsync` reverts it. ```csharp using System.Threading.Tasks; using AdaskoTheBeAsT.MongoDbMigrations.Abstractions; using MongoDB.Bson; using MongoDB.Driver; // Migration 1: Rename a field public class RenameNameToFirstName : IMigration { public Version Version => new Version(1, 0, 0); public string Name => "Rename name column to firstName"; public Task UpAsync(MigrationContext context) { var collection = context.Database.GetCollection("clients"); return collection.UpdateManyAsync( FilterDefinition.Empty, Builders.Update.Rename("name", "firstName"), cancellationToken: context.CancellationToken); } public Task DownAsync(MigrationContext context) { var collection = context.Database.GetCollection("clients"); return collection.UpdateManyAsync( FilterDefinition.Empty, Builders.Update.Rename("firstName", "name"), cancellationToken: context.CancellationToken); } } ``` -------------------------------- ### Add Field with Default Value Migration in C# Source: https://context7.com/adaskothebeast/adaskothebeast.mongodbmigrations/llms.txt This migration adds a 'status' field with a default value of 'pending' to documents in the 'orders' collection where the field does not already exist. `DownAsync` removes the field. ```csharp using System.Threading.Tasks; using AdaskoTheBeAsT.MongoDbMigrations.Abstractions; using MongoDB.Bson; using MongoDB.Driver; // Migration 4: Add new field with default value public class AddStatusField : IMigration { public Version Version => new Version(2, 0, 0); public string Name => "Add status field with default value"; public Task UpAsync(MigrationContext context) { var collection = context.Database.GetCollection("orders"); return collection.UpdateManyAsync( Builders.Filter.Exists("status", false), Builders.Update.Set("status", "pending"), cancellationToken: context.CancellationToken); } public Task DownAsync(MigrationContext context) { var collection = context.Database.GetCollection("orders"); return collection.UpdateManyAsync( FilterDefinition.Empty, Builders.Update.Unset("status"), cancellationToken: context.CancellationToken); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.