### Start Temporary MongoDB Server (Sync) Source: https://context7.com/asimmon/ephemeral-mongo/llms.txt Use the synchronous MongoRunner.Run() method when async/await is not preferred or available. This method starts a disposable MongoDB instance and returns an IMongoRunner for managing the server lifecycle. Ensure proper disposal to clean up resources. ```csharp using EphemeralMongo; using MongoDB.Driver; // Synchronous startup using var runner = MongoRunner.Run(); var client = new MongoClient(runner.ConnectionString); var database = client.GetDatabase("myapp"); database.CreateCollection("products"); var collection = database.GetCollection("products"); collection.InsertOne(new Product { Id = "SKU001", Name = "Widget", Price = 29.99m }); var product = collection.Find(p => p.Id == "SKU001").FirstOrDefault(); Console.WriteLine($"Found: {product.Name} - ${product.Price}"); // Output: Found: Widget - $29.99 public record Product { public string Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } } ``` -------------------------------- ### Start Temporary MongoDB Server (Async) Source: https://context7.com/asimmon/ephemeral-mongo/llms.txt Use MongoRunner.RunAsync to start a disposable MongoDB instance with default settings. The IMongoRunner automatically cleans up the MongoDB process and data directory upon disposal. This is suitable for integration tests requiring MongoDB interaction. ```csharp using EphemeralMongo; using MongoDB.Driver; // Start MongoDB with default settings (MongoDB 8, Community edition) using var runner = await MongoRunner.RunAsync(); // Access the connection string Console.WriteLine($"MongoDB running at: {runner.ConnectionString}"); // Output: mongodb://127.0.0.1:54321 // Use with MongoDB C# driver var client = new MongoClient(runner.ConnectionString); var database = client.GetDatabase("testdb"); var collection = database.GetCollection("users"); await collection.InsertOneAsync(new BsonDocument { { "name", "John Doe" }, { "email", "john@example.com" } }); var user = await collection.Find(Builders.Filter.Empty).FirstOrDefaultAsync(); Console.WriteLine(user); // Output: { "_id" : ObjectId("..."), "name" : "John Doe", "email" : "john@example.com" } // MongoDB process is automatically stopped and data directory cleaned up when disposed ``` -------------------------------- ### MongoRunner.RunAsync - Start a Temporary MongoDB Server Source: https://context7.com/asimmon/ephemeral-mongo/llms.txt The primary entry point for starting a disposable MongoDB instance asynchronously. It downloads MongoDB binaries if needed, starts a mongod process on an available port, and returns an IMongoRunner that automatically cleans up when disposed. ```APIDOC ## MongoRunner.RunAsync - Start a Temporary MongoDB Server ### Description Starts a disposable MongoDB instance asynchronously. Downloads binaries if needed, starts a mongod process on an available port, and returns an `IMongoRunner` that automatically cleans up when disposed. ### Method `async Task` ### Endpoint N/A (Library method) ### Parameters None ### Request Example ```csharp using EphemeralMongo; using MongoDB.Driver; // Start MongoDB with default settings (MongoDB 8, Community edition) using var runner = await MongoRunner.RunAsync(); // Access the connection string Console.WriteLine($"MongoDB running at: {runner.ConnectionString}"); // Use with MongoDB C# driver var client = new MongoClient(runner.ConnectionString); var database = client.GetDatabase("testdb"); var collection = database.GetCollection("users"); await collection.InsertOneAsync(new BsonDocument { { "name", "John Doe" }, { "email", "john@example.com" } }); var user = await collection.Find(Builders.Filter.Empty).FirstOrDefaultAsync(); Console.WriteLine(user); // MongoDB process is automatically stopped and data directory cleaned up when disposed ``` ### Response #### Success Response (IMongoRunner) - **ConnectionString** (string) - The connection string for the running MongoDB instance. #### Response Example ```json { "ConnectionString": "mongodb://127.0.0.1:54321" } ``` ``` -------------------------------- ### Run and Use MongoRunner Source: https://github.com/asimmon/ephemeral-mongo/blob/main/README.md Start a MongoDB instance asynchronously, get its connection string, interact with the database, and perform import/export operations. The runner is disposed automatically, stopping the process and cleaning up data. ```csharp // Disposing the runner will kill the MongoDB process (mongod) and delete the associated data directory using (await var runner = MongoRunner.RunAsync(options)) { var database = new MongoClient(runner.ConnectionString).GetDatabase("default"); // Do something with the database database.CreateCollection("people"); // Export a collection to a file. A synchronous version is also available. await runner.ExportAsync("default", "people", "/path/to/default.json"); // Import a collection from a file. A synchronous version is also available. await runner.ImportAsync("default", "people", "/path/to/default.json"); } ``` -------------------------------- ### Run a Temporary MongoDB Server Source: https://github.com/asimmon/ephemeral-mongo/blob/main/README.md Use this snippet to quickly start a temporary MongoDB server. The server will be automatically stopped and cleaned up when the runner is disposed. Connection string is provided for access. ```csharp using var runner = await MongoRunner.RunAsync(); Console.WriteLine(runner.ConnectionString); ``` -------------------------------- ### MongoRunner.Run - Synchronous MongoDB Server Start Source: https://context7.com/asimmon/ephemeral-mongo/llms.txt Synchronous version of RunAsync for scenarios where async/await is not available or preferred. It starts a disposable MongoDB instance synchronously. ```APIDOC ## MongoRunner.Run - Synchronous MongoDB Server Start ### Description Starts a disposable MongoDB instance synchronously. This is useful for scenarios where async/await is not available or preferred. ### Method `IMongoRunner` ### Endpoint N/A (Library method) ### Parameters None ### Request Example ```csharp using EphemeralMongo; using MongoDB.Driver; // Synchronous startup using var runner = MongoRunner.Run(); var client = new MongoClient(runner.ConnectionString); var database = client.GetDatabase("myapp"); database.CreateCollection("products"); var collection = database.GetCollection("products"); collection.InsertOne(new Product { Id = "SKU001", Name = "Widget", Price = 29.99m }); var product = collection.Find(p => p.Id == "SKU001").FirstOrDefault(); Console.WriteLine($"Found: {product.Name} - ${product.Price}"); public record Product { public string Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } } ``` ### Response #### Success Response (IMongoRunner) - **ConnectionString** (string) - The connection string for the running MongoDB instance. #### Response Example ```json { "ConnectionString": "mongodb://127.0.0.1:54321" } ``` ``` -------------------------------- ### Running EphemeralMongo Source: https://github.com/asimmon/ephemeral-mongo/blob/main/src/EphemeralMongo/PublicAPI.Shipped.txt Provides methods to start and manage an ephemeral MongoDB instance. ```APIDOC ## Running EphemeralMongo ### Description Methods to start and manage an ephemeral MongoDB instance. ### Method `static EphemeralMongo.MongoRunner.Run(EphemeralMongo.MongoRunnerOptions? options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> EphemeralMongo.IMongoRunner!` ### Endpoint N/A (In-process execution) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) Returns an `IMongoRunner` instance that can be used to interact with the running MongoDB instance. #### Response Example ```csharp // Example usage: var runner = EphemeralMongo.MongoRunner.Run(); // Use runner to interact with MongoDB ``` ```APIDOC ## Running EphemeralMongo Asynchronously ### Description Asynchronously starts and manages an ephemeral MongoDB instance. ### Method `static EphemeralMongo.MongoRunner.RunAsync(EphemeralMongo.MongoRunnerOptions? options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!` ### Endpoint N/A (In-process execution) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) Returns a `Task` that completes with an `IMongoRunner` instance that can be used to interact with the running MongoDB instance. #### Response Example ```csharp // Example usage: var runner = await EphemeralMongo.MongoRunner.RunAsync(); // Use runner to interact with MongoDB ``` -------------------------------- ### xUnit Integration with EphemeralMongo Source: https://context7.com/asimmon/ephemeral-mongo/llms.txt Demonstrates setting up and tearing down an EphemeralMongo instance for xUnit integration tests. Requires implementing IAsyncLifetime for proper resource management. ```csharp using EphemeralMongo; using MongoDB.Driver; using Xunit; public class UserRepositoryTests : IAsyncLifetime { private IMongoRunner _runner = null!; private IMongoDatabase _database = null!; public async Task InitializeAsync() { var options = new MongoRunnerOptions { Version = MongoVersion.V8, UseSingleNodeReplicaSet = true, AdditionalArguments = ["--quiet"], StandardErrorLogger = Console.Error.WriteLine }; _runner = await MongoRunner.RunAsync(options); _database = new MongoClient(_runner.ConnectionString).GetDatabase("test"); } public Task DisposeAsync() { _runner?.Dispose(); return Task.CompletedTask; } [Fact] public async Task CreateUser_ShouldPersistUser() { // Arrange var users = _database.GetCollection("users"); var newUser = new User { Id = "user-1", Email = "test@example.com", Name = "Test User" }; // Act await users.InsertOneAsync(newUser); var retrieved = await users.Find(u => u.Id == "user-1").FirstOrDefaultAsync(); // Assert Assert.NotNull(retrieved); Assert.Equal("test@example.com", retrieved.Email); Assert.Equal("Test User", retrieved.Name); } [Fact] public async Task UpdateUser_WithTransaction_ShouldCommitChanges() { // Arrange var users = _database.GetCollection("users"); var auditLog = _database.GetCollection("audit"); await users.InsertOneAsync(new User { Id = "user-2", Email = "old@example.com", Name = "User" }); // Act - Use transaction (requires replica set) var client = new MongoClient(_runner.ConnectionString); using var session = await client.StartSessionAsync(); session.StartTransaction(); await users.UpdateOneAsync(session, Builders.Filter.Eq(u => u.Id, "user-2"), Builders.Update.Set(u => u.Email, "new@example.com")); await auditLog.InsertOneAsync(session, new AuditEntry { UserId = "user-2", Action = "email_updated", Timestamp = DateTime.UtcNow }); await session.CommitTransactionAsync(); // Assert var updatedUser = await users.Find(u => u.Id == "user-2").FirstOrDefaultAsync(); var logEntry = await auditLog.Find(a => a.UserId == "user-2").FirstOrDefaultAsync(); Assert.Equal("new@example.com", updatedUser?.Email); Assert.NotNull(logEntry); } public record User { public string Id { get; set; } = string.Empty; public string Email { get; set; } = string.Empty; public string Name { get; set; } = string.Empty; } public record AuditEntry { public string UserId { get; set; } = string.Empty; public string Action { get; set; } = string.Empty; public DateTime Timestamp { get; set; } } } ``` -------------------------------- ### Rent and Return MongoRunner Instances Source: https://github.com/asimmon/ephemeral-mongo/blob/main/README.md Demonstrates using PooledMongoRunner to rent and return MongoRunner instances. This helps reuse mongod processes, but new instances are created if a runner is rented too many times. Ensure runners are returned to the pool. ```csharp var options = new MongoRunnerOptions { Version = MongoVersion.V7, UseSingleNodeReplicaSet = true }; using var pool = new MongoRunnerPool(options); var runner1 = await pool.RentAsync(); var runner2 = await pool.RentAsync(); try { // Same connection string, same mongod process Console.WriteLine(runner1.ConnectionString); Console.WriteLine(runner2.ConnectionString); } finally { pool.Return(runner1); pool.Return(runner2); } // This is a new mongod process var runner3 = await pool.RentAsync(); ``` -------------------------------- ### Configure MongoRunnerOptions for MongoDB Instance Source: https://context7.com/asimmon/ephemeral-mongo/llms.txt Customize MongoDB instance settings like version, edition, replica set mode, ports, timeouts, and logging. Ensure necessary imports are included. ```csharp using EphemeralMongo; using MongoDB.Driver; var options = new MongoRunnerOptions { // MongoDB version: V6, V7, or V8 (default: V8) Version = MongoVersion.V8, // Edition: Community or Enterprise (default: Community) Edition = MongoEdition.Community, // Enable single-node replica set for transactions and change streams UseSingleNodeReplicaSet = true, // Specific port (default: random available port) MongoPort = 27017, // Additional mongod CLI arguments AdditionalArguments = ["--quiet"], // Custom data directory (default: auto-generated temp directory) DataDirectory = "/path/to/data/", // Use pre-downloaded MongoDB binaries BinaryDirectory = "/path/to/mongo/bin/", // Logging delegates for mongod output StandardOutputLogger = Console.WriteLine, StandardErrorLogger = Console.Error.WriteLine, // Timeout for MongoDB to start accepting connections ConnectionTimeout = TimeSpan.FromSeconds(30), // Timeout for replica set initialization ReplicaSetSetupTimeout = TimeSpan.FromSeconds(10), // Auto-cleanup temp directories older than this DataDirectoryLifetime = TimeSpan.FromHours(12) }; using var runner = await MongoRunner.RunAsync(options); // With replica set enabled, transactions are supported var client = new MongoClient(runner.ConnectionString); var database = client.GetDatabase("shop"); var orders = database.GetCollection("orders"); var inventory = database.GetCollection("inventory"); using var session = await client.StartSessionAsync(); session.StartTransaction(); try { await orders.InsertOneAsync(session, new BsonDocument { { "item", "widget" }, { "qty", 5 } }); await inventory.UpdateOneAsync(session, Builders.Filter.Eq("item", "widget"), Builders.Update.Inc("stock", -5)); await session.CommitTransactionAsync(); Console.WriteLine("Transaction committed successfully"); } catch { await session.AbortTransactionAsync(); throw; } ``` -------------------------------- ### Configure MongoRunner Options Source: https://github.com/asimmon/ephemeral-mongo/blob/main/README.md Customize MongoDB server settings like version, edition, replica set, arguments, ports, and timeouts. Defaults are applied if not specified. ```csharp // All the following properties are OPTIONAL. var options = new MongoRunnerOptions { // The desired MongoDB version to download and use. // Possible values are V6, V7 and V8. Default is V8. Version = MongoVersion.V8, // The desired MongoDB edition to download and use. // Possible values are Community and Enterprise. Default is Community. Edition = MongoEdition.Community, // If true, the MongoDB server will run as a single-node replica set. Default is false. UseSingleNodeReplicaSet = true, // Additional arguments to pass to the MongoDB server. Default is null. AdditionalArguments = ["--quiet"], // The port on which the MongoDB server will listen. // Default is null, which means a random available port will be assigned. MongoPort = 27017, // The directory where the MongoDB server will store its data. // Default is null, which means a temporary directory will be created. DataDirectory = "/path/to/data/", // Provide your own MongoDB binaries in this directory. // Default is null, which means the library will download them automatically. BinaryDirectory = "/path/to/mongo/bin/", // A delegate that receives the MongoDB server's standard output. StandardOutputLogger = Console.WriteLine, // A delegate that receives the MongoDB server's standard error output. StandardErrorLogger = Console.WriteLine, // Timeout for the MongoDB server to start. Default is 30 seconds. ConnectionTimeout = TimeSpan.FromSeconds(10), // Timeout for the replica set to be initialized. Default is 10 seconds. ReplicaSetSetupTimeout = TimeSpan.FromSeconds(5), // The duration for which temporary data directories will be kept. // Ignored when you provide your own data directory. Default is 12 hours. DataDirectoryLifetime = TimeSpan.FromDays(1), // Override this property to provide your own HTTP transport. // Useful when behind a proxy or firewall. Default is a shared reusable instance. Transport = new HttpTransport(new HttpClient()), // Delay before checking for a new version of the MongoDB server. Default is 1 day. NewVersionCheckTimeout = TimeSpan.FromDays(2) }; ``` -------------------------------- ### MongoRunnerPool Constructor Source: https://github.com/asimmon/ephemeral-mongo/blob/main/src/EphemeralMongo/PublicAPI.Unshipped.txt Initializes a new instance of the MongoRunnerPool class with specified options and maximum rentals per runner. ```APIDOC ## MongoRunnerPool Constructor ### Description Initializes a new instance of the MongoRunnerPool class. ### Method Constructor ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Reuse MongoDB Instances with MongoRunnerPool Source: https://context7.com/asimmon/ephemeral-mongo/llms.txt Demonstrates using `MongoRunnerPool` to reuse MongoDB instances across tests, reducing startup overhead. Runners are rented and returned to the pool, with a configurable limit on rentals per runner before a new instance is created. The pool manages disposal of all underlying mongod processes upon its own disposal. ```csharp using EphemeralMongo; using MongoDB.Driver; #pragma warning disable EMEX0001 // Experimental API var options = new MongoRunnerOptions { Version = MongoVersion.V8, UseSingleNodeReplicaSet = true, AdditionalArguments = ["--quiet"] }; // Create a pool with max 100 rentals per runner (default) using var pool = new MongoRunnerPool(options, maxRentalsPerRunner: 100); // Rent runners for concurrent test execution var runner1 = await pool.RentAsync(); var runner2 = await pool.RentAsync(); // Same underlying mongod process, same connection string Console.WriteLine($"Runner 1: {runner1.ConnectionString}"); Console.WriteLine($"Runner 2: {runner2.ConnectionString}"); // Both output the same connection string try { // Use separate databases for test isolation var client1 = new MongoClient(runner1.ConnectionString); var client2 = new MongoClient(runner2.ConnectionString); var db1 = client1.GetDatabase("test_user_service"); var db2 = client2.GetDatabase("test_order_service"); await db1.GetCollection("users") .InsertOneAsync(new BsonDocument { { "name", "Test User" } }); await db2.GetCollection("orders") .InsertOneAsync(new BsonDocument { { "product", "Widget" }, { "qty", 3 } }); Console.WriteLine("Both tests completed with isolated databases"); } finally { // Return runners to pool (does not dispose underlying mongod) pool.Return(runner1); pool.Return(runner2); } // After maxRentalsPerRunner is reached, a new mongod process is created var runner3 = await pool.RentAsync(); pool.Return(runner3); // Pool.Dispose() cleans up all underlying mongod processes #pragma warning restore EMEX0001 ``` -------------------------------- ### MongoRunnerOptions Configuration Source: https://github.com/asimmon/ephemeral-mongo/blob/main/src/EphemeralMongo/PublicAPI.Shipped.txt Details on configuring the `MongoRunnerOptions` for customizing the ephemeral MongoDB instance. ```APIDOC ## MongoRunnerOptions ### Description Provides options for configuring the `MongoRunner`. ### Method `EphemeralMongo.MongoRunnerOptions.MongoRunnerOptions() -> void` ### Endpoint N/A (Class constructor) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) N/A #### Response Example None ``` ```APIDOC ## MongoRunnerOptions Properties ### Description Configurable properties for `MongoRunnerOptions`. ### Properties - **AdditionalArguments** (`string![]?`) - Additional command-line arguments for the MongoDB process. - **BinaryDirectory** (`string?`) - Path to the MongoDB binaries. - **ConnectionTimeout** (`System.TimeSpan`) - Timeout for establishing a connection. - **DataDirectory** (`string?`) - Directory for MongoDB data files. - **DataDirectoryLifetime** (`System.TimeSpan?`) - Lifetime of the data directory. - **Edition** (`EphemeralMongo.MongoEdition`) - Edition of MongoDB to run (Community or Enterprise). - **MongoPort** (`int?`) - Port for the MongoDB instance. - **NewVersionCheckTimeout** (`System.TimeSpan`) - Timeout for checking for new versions. - **ReplicaSetSetupTimeout** (`System.TimeSpan`) - Timeout for setting up a replica set. - **StandardErrorLogger** (`EphemeralMongo.Logger?`) - Logger for standard error output. - **StandardOutputLogger** (`EphemeralMongo.Logger?`) - Logger for standard output. - **Transport** (`EphemeralMongo.HttpTransport!`) - Transport mechanism for communication. - **UseSingleNodeReplicaSet** (`bool`) - Whether to use a single-node replica set. - **Version** (`EphemeralMongo.MongoVersion`) - Version of MongoDB to run (e.g., V6, V7, V8). ### Example Usage ```csharp var options = new EphemeralMongo.MongoRunnerOptions { Edition = EphemeralMongo.MongoEdition.Enterprise, Version = EphemeralMongo.MongoVersion.V7, DataDirectory = "/path/to/data", ConnectionTimeout = TimeSpan.FromSeconds(30) }; var runner = EphemeralMongo.MongoRunner.Run(options); ``` ``` -------------------------------- ### MongoRunnerPool.RentAsync() Source: https://github.com/asimmon/ephemeral-mongo/blob/main/src/EphemeralMongo/PublicAPI.Unshipped.txt Asynchronously rents a MongoDB runner from the pool. ```APIDOC ## MongoRunnerPool.RentAsync() ### Description Asynchronously rents a MongoDB runner from the pool. ### Method System.Threading.Tasks.Task ### Parameters #### Path Parameters None #### Query Parameters - **cancellationToken** (System.Threading.CancellationToken) - Optional - A token to observe for cancellation. ### Request Example None ### Response #### Success Response (200) - **Task** (System.Threading.Tasks.Task) - A task that represents the asynchronous operation. The value of the task contains the rented MongoDB runner. #### Response Example None ``` -------------------------------- ### MongoRunnerPool.Rent() Source: https://github.com/asimmon/ephemeral-mongo/blob/main/src/EphemeralMongo/PublicAPI.Unshipped.txt Rents a MongoDB runner from the pool. ```APIDOC ## MongoRunnerPool.Rent() ### Description Rents a MongoDB runner from the pool. ### Method EphemeralMongo.IMongoRunner ### Parameters #### Path Parameters None #### Query Parameters - **cancellationToken** (System.Threading.CancellationToken) - Optional - A token to observe for cancellation. ### Request Example None ### Response #### Success Response (200) - **IMongoRunner** (EphemeralMongo.IMongoRunner) - The rented MongoDB runner. #### Response Example None ``` -------------------------------- ### MongoRunnerPool.Return() Source: https://github.com/asimmon/ephemeral-mongo/blob/main/src/EphemeralMongo/PublicAPI.Unshipped.txt Returns a previously rented MongoDB runner to the pool. ```APIDOC ## MongoRunnerPool.Return() ### Description Returns a previously rented MongoDB runner to the pool. ### Method void ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **runner** (EphemeralMongo.IMongoRunner!) - Required - The MongoDB runner to return. ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Configure Enterprise Edition with In-Memory Storage Source: https://context7.com/asimmon/ephemeral-mongo/llms.txt Utilize MongoDB Enterprise edition with the in-memory storage engine for enhanced test execution speed. Ensure necessary imports are present. ```csharp using EphemeralMongo; using MongoDB.Driver; var options = new MongoRunnerOptions { Edition = MongoEdition.Enterprise, AdditionalArguments = ["--storageEngine", "inMemory", "--quiet"], UseSingleNodeReplicaSet = true }; using var runner = await MongoRunner.RunAsync(options); var client = new MongoClient(runner.ConnectionString); var database = client.GetDatabase("performance_test"); var collection = database.GetCollection("metrics"); // In-memory storage is significantly faster for tests var documents = Enumerable.Range(0, 10000) .Select(i => new BsonDocument { { "index", i }, { "value", i * 1.5 } }) .ToList(); await collection.InsertManyAsync(documents); var count = await collection.CountDocumentsAsync(FilterDefinition.Empty); Console.WriteLine($"Inserted {count} documents"); // Output: Inserted 10000 documents ``` -------------------------------- ### Configure Enterprise Edition with In-Memory Storage Source: https://github.com/asimmon/ephemeral-mongo/blob/main/README.md Run MongoDB Enterprise edition with the in-memory storage engine for improved performance in testing scenarios. Ensure you comply with MongoDB Enterprise licensing. ```csharp var options = new MongoRunnerOptions { Edition = MongoEdition.Enterprise, AdditionalArguments = ["--storageEngine", "inMemory"], }; using var runner = await MongoRunner.RunAsync(options); // [...] ``` -------------------------------- ### Import Data from JSON File using ImportAsync Source: https://context7.com/asimmon/ephemeral-mongo/llms.txt Import a MongoDB collection from a JSON file using the `mongoimport` tool. Supports additional arguments and an optional drop mode for existing collections. Ensure the sample data file exists. ```csharp using EphemeralMongo; using MongoDB.Driver; // Sample data file: /tmp/users.json // [{"_id": "1", "name": "Alice"}, {"_id": "2", "name": "Bob"}] using var runner = await MongoRunner.RunAsync(); // Import with JSON array format await runner.ImportAsync( database: "myapp", collection: "users", inputFilePath: "/tmp/users.json", additionalArguments: ["--jsonArray"], drop: false // Set to true to drop existing collection first ); // Verify imported data var client = new MongoClient(runner.ConnectionString); var collection = client.GetDatabase("myapp").GetCollection("users"); var users = await collection.Find(FilterDefinition.Empty).ToListAsync(); foreach (var user in users) { Console.WriteLine(user); } // Output: // { "_id" : "1", "name" : "Alice" } // { "_id" : "2", "name" : "Bob" } // Synchronous version runner.Import("myapp", "users", "/tmp/more_users.json", ["--jsonArray"], drop: true); ``` -------------------------------- ### MongoRunnerPool.Dispose() Source: https://github.com/asimmon/ephemeral-mongo/blob/main/src/EphemeralMongo/PublicAPI.Unshipped.txt Releases all resources used by the MongoRunnerPool. ```APIDOC ## MongoRunnerPool.Dispose() ### Description Releases all resources used by the MongoRunnerPool. ### Method void ### Parameters None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Import and Export Operations Source: https://github.com/asimmon/ephemeral-mongo/blob/main/src/EphemeralMongo/PublicAPI.Shipped.txt APIs for importing data into and exporting data from an ephemeral MongoDB instance. ```APIDOC ## Import Data into MongoDB ### Description Imports data from a specified file path into a MongoDB database and collection. ### Method `EphemeralMongo.IMongoRunner.Import(string! database, string! collection, string! inputFilePath, string![]? additionalArguments = null, bool drop = false, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> void` ### Endpoint N/A (In-process execution) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) Indicates successful import. #### Response Example None ``` ```APIDOC ## Import Data into MongoDB Asynchronously ### Description Asynchronously imports data from a specified file path into a MongoDB database and collection. ### Method `EphemeralMongo.IMongoRunner.ImportAsync(string! database, string! collection, string! inputFilePath, string![]? additionalArguments = null, bool drop = false, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!` ### Endpoint N/A (In-process execution) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) Returns a `Task` that completes when the import operation is successful. #### Response Example None ``` ```APIDOC ## Export Data from MongoDB ### Description Exports data from a specified MongoDB database and collection to a file path. ### Method `EphemeralMongo.IMongoRunner.Export(string! database, string! collection, string! outputFilePath, string![]? additionalArguments = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> void` ### Endpoint N/A (In-process execution) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) Indicates successful export. #### Response Example None ``` ```APIDOC ## Export Data from MongoDB Asynchronously ### Description Asynchronously exports data from a specified MongoDB database and collection to a file path. ### Method `EphemeralMongo.IMongoRunner.ExportAsync(string! database, string! collection, string! outputFilePath, string![]? additionalArguments = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task!` ### Endpoint N/A (In-process execution) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) Returns a `Task` that completes when the export operation is successful. #### Response Example None ``` -------------------------------- ### Export Collection to JSON Array Format Source: https://context7.com/asimmon/ephemeral-mongo/llms.txt Exports a MongoDB collection to a JSON file. Supports additional arguments like '--jsonArray' and '--pretty'. The asynchronous `ExportAsync` is shown, followed by the synchronous `Export` method. ```csharp using EphemeralMongo; using MongoDB.Driver; using var runner = await MongoRunner.RunAsync(); var client = new MongoClient(runner.ConnectionString); var database = client.GetDatabase("analytics"); var events = database.GetCollection("events"); // Insert sample data await events.InsertManyAsync(new[] { new BsonDocument { { "type", "click" }, { "page", "/home" }, { "timestamp", DateTime.UtcNow } }, new BsonDocument { { "type", "view" }, { "page", "/products" }, { "timestamp", DateTime.UtcNow } }, new BsonDocument { { "type", "click" }, { "page", "/checkout" }, { "timestamp", DateTime.UtcNow } } }); // Export to JSON array format var exportPath = Path.Combine(Path.GetTempPath(), "events_export.json"); await runner.ExportAsync( database: "analytics", collection: "events", outputFilePath: exportPath, additionalArguments: ["--jsonArray", "--pretty"] ); Console.WriteLine($"Exported to: {exportPath}"); Console.WriteLine(File.ReadAllText(exportPath)); // Output: JSON array of exported documents // Synchronous version runner.Export("analytics", "events", "/tmp/events_backup.json", ["--jsonArray"]); ``` -------------------------------- ### Logger Interface Source: https://github.com/asimmon/ephemeral-mongo/blob/main/src/EphemeralMongo/PublicAPI.Shipped.txt Interface for logging messages within EphemeralMongo. ```APIDOC ## Logger Interface ### Description Interface for implementing custom logging for EphemeralMongo. ### Method - `virtual EphemeralMongo.Logger.Invoke(string! text) -> void` ### Example Usage ```csharp public class CustomLogger : EphemeralMongo.Logger { public override void Invoke(string text) { Console.WriteLine($"[LOG]: {text}"); } } var logger = new CustomLogger(); var options = new EphemeralMongo.MongoRunnerOptions { StandardOutputLogger = logger }; ``` ``` -------------------------------- ### MongoVersion Enum Source: https://github.com/asimmon/ephemeral-mongo/blob/main/src/EphemeralMongo/PublicAPI.Shipped.txt Defines the available versions for MongoDB. ```APIDOC ## MongoVersion Enum ### Description Enumeration representing the available MongoDB versions. ### Values - **V6** (`6`) - **V7** (`7`) - **V8** (`8`) ### Example Usage ```csharp var options = new EphemeralMongo.MongoRunnerOptions { Version = EphemeralMongo.MongoVersion.V7 }; ``` ``` -------------------------------- ### HttpTransport Source: https://github.com/asimmon/ephemeral-mongo/blob/main/src/EphemeralMongo/PublicAPI.Shipped.txt Transport mechanism for HTTP communication within EphemeralMongo. ```APIDOC ## HttpTransport ### Description Handles HTTP transport for EphemeralMongo. ### Constructors - `EphemeralMongo.HttpTransport(System.Net.Http.HttpClient! httpClient) -> void` - `EphemeralMongo.HttpTransport(System.Net.Http.HttpMessageHandler! handler) -> void` ### Example Usage ```csharp var httpClient = new System.Net.Http.HttpClient(); var transport = new EphemeralMongo.HttpTransport(httpClient); var options = new EphemeralMongo.MongoRunnerOptions { Transport = transport }; ``` ``` -------------------------------- ### EphemeralMongoException Source: https://github.com/asimmon/ephemeral-mongo/blob/main/src/EphemeralMongo/PublicAPI.Shipped.txt Custom exception class for EphemeralMongo operations. ```APIDOC ## EphemeralMongoException ### Description Custom exception class for errors occurring within EphemeralMongo. ### Constructors - `EphemeralMongo.EphemeralMongoException(string! message) -> void` - `EphemeralMongo.EphemeralMongoException(string! message, System.Exception! innerException) -> void` ### Example Usage ```csharp try { // Some operation that might throw an exception } catch (EphemeralMongo.EphemeralMongoException ex) { Console.WriteLine($"EphemeralMongo Error: {ex.Message}"); } ``` ``` -------------------------------- ### MongoEdition Enum Source: https://github.com/asimmon/ephemeral-mongo/blob/main/src/EphemeralMongo/PublicAPI.Shipped.txt Defines the available editions for MongoDB. ```APIDOC ## MongoEdition Enum ### Description Enumeration representing the available MongoDB editions. ### Values - **Community** (`0`) - **Enterprise** (`1`) ### Example Usage ```csharp var options = new EphemeralMongo.MongoRunnerOptions { Edition = EphemeralMongo.MongoEdition.Enterprise }; ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.