### YAML Test Structure Example Source: https://github.com/mongodb/mongo-csharp-driver/blob/main/specifications/server-discovery-and-monitoring/tests/README.rst Illustrates the basic structure of a YAML test file, including description, URI, and phases. ```yaml description: "A textual description of the test." uri: "A connection string." phases: - description: "(optional) A textual description of this phase." responses: [] applicationErrors: [] outcome: {} ``` -------------------------------- ### YAML Phase Response Example Source: https://github.com/mongodb/mongo-csharp-driver/blob/main/specifications/server-discovery-and-monitoring/tests/README.rst Shows how to define a response within a test phase, including the source address and the hello response. ```yaml responses: - source: "a:27017" response: "{ok: 1, helloOk: true, isWritablePrimary: true}" ``` -------------------------------- ### YAML ServerDescription Example Source: https://github.com/mongodb/mongo-csharp-driver/blob/main/specifications/server-discovery-and-monitoring/tests/README.rst Defines the expected ServerDescription within a TopologyDescription outcome. ```yaml servers: "a:27017": type: "RSSecondary" setName: "rs0" setVersion: 1 electionId: null minWireVersion: 0 maxWireVersion: 9 pool: generation: 0 ``` -------------------------------- ### Watch All Collections in a Database Source: https://context7.com/mongodb/mongo-csharp-driver/llms.txt This example shows how to set up a change stream to monitor all collections within a specific database. It uses `db.WatchAsync` with an empty pipeline. ```csharp // Watch all collections in a database using var dbCursor = await db.WatchAsync>( new EmptyPipelineDefinition>()); ``` -------------------------------- ### Start a new thread Source: https://github.com/mongodb/mongo-csharp-driver/blob/main/specifications/server-discovery-and-monitoring/tests/README.rst The 'startThread' operation initiates a new thread with a specified name. This name is used by 'runOnThread' and 'waitForThread'. ```yaml - name: startThread object: testRunner arguments: name: thread1 ``` -------------------------------- ### Build Lambda Application with SAM CLI Source: https://github.com/mongodb/mongo-csharp-driver/blob/main/tests/FaasTests/LambdaTests/README.md Use 'sam build' to install dependencies, create a deployment package, and prepare your Lambda function for local testing or deployment. Ensure your project's .csproj file lists all necessary dependencies. ```bash sam build ``` -------------------------------- ### Get Database using GetDatabase method Source: https://github.com/mongodb/mongo-csharp-driver/blob/main/Release Notes/Release Notes v1.8.md Use the GetDatabase method to retrieve a database instance. This replaces the deprecated indexer access. ```csharp var database = server.GetDatabase("test"); ``` -------------------------------- ### Run Driver Benchmarks Source: https://github.com/mongodb/mongo-csharp-driver/blob/main/benchmarks/MongoDB.Driver.Benchmarks/README.md Execute the benchmark runner for driver-specific benchmarks. This command starts the benchmark runner and allows selection via console prompts. Ensure a mongod instance is running or specify a custom connection string via the MONGODB_URI environment variable. ```bash dotnet run -c Release -- --driverBenchmarks ``` -------------------------------- ### View Available Benchmark Options Source: https://github.com/mongodb/mongo-csharp-driver/blob/main/benchmarks/MongoDB.Driver.Benchmarks/README.md Display a list of all available command-line options for the benchmark runner. This is useful for understanding the full range of customization available for running benchmarks. ```bash dotnet run -c Release -- --help ``` -------------------------------- ### Initialize C# Driver (Recommended) Source: https://github.com/mongodb/mongo-csharp-driver/blob/main/Release Notes/Release Notes v1.7.md This is the new recommended way to initialize the C# driver using MongoClient. It defaults to an Acknowledged WriteConcern. ```csharp var connectionString = "mongodb://localhost"; var client = new MongoClient(connectionString); var server = client.GetServer(); var database = server.GetDatabase("test"); // WriteConcern defaulted to Acknowledged ``` -------------------------------- ### YAML Outcome TopologyDescription Example Source: https://github.com/mongodb/mongo-csharp-driver/blob/main/specifications/server-discovery-and-monitoring/tests/README.rst Specifies the expected TopologyDescription outcome for a non-monitoring test. ```yaml outcome: topologyType: "ReplicaSetNoPrimary" setName: null servers: {} logicalSessionTimeoutMinutes: null ``` -------------------------------- ### MongoClient - Connecting to MongoDB Source: https://context7.com/mongodb/mongo-csharp-driver/llms.txt Demonstrates how to create a MongoClient instance using various connection methods, including connection strings and programmatic settings. It also shows how to list and drop databases. ```APIDOC ## MongoClient — Connecting to MongoDB `MongoClient` is the entry point for all driver operations. A single `MongoClient` instance is thread-safe and should be shared across the application lifetime. It accepts a connection string or a `MongoClientSettings` object. ```csharp using MongoDB.Driver; // Simple connection string var client = new MongoClient("mongodb://localhost:27017"); // Atlas cluster with credentials var client = new MongoClient( "mongodb+srv://user:password@cluster0.example.mongodb.net/?retryWrites=true&w=majority"); // Programmatic settings with advanced options var settings = new MongoClientSettings { Servers = new[] { new MongoServerAddress("localhost", 27017) }, ReplicaSetName = "rs0", ReadPreference = ReadPreference.SecondaryPreferred, WriteConcern = WriteConcern.WMajority, RetryWrites = true, RetryReads = true, ServerApi = new ServerApi(ServerApiVersion.V1, strict: true), ApplicationName = "MyApp" }; var client = new MongoClient(settings); // List databases var cursor = client.ListDatabaseNames(); foreach (var name in cursor.ToEnumerable()) Console.WriteLine(name); // admin, local, mydb // Drop a database await client.DropDatabaseAsync("mydb"); ``` ``` -------------------------------- ### Type Query with OfType() Source: https://github.com/mongodb/mongo-csharp-driver/blob/main/Release Notes/Release Notes v1.5.md Example of performing a type query using the OfType() LINQ operator on a collection. ```csharp collection.AsQueryable().OfType() ``` -------------------------------- ### YAML Application Error Example Source: https://github.com/mongodb/mongo-csharp-driver/blob/main/specifications/server-discovery-and-monitoring/tests/README.rst Defines an application error to be mocked during testing, specifying the address, type, and when it should occur. ```yaml applicationErrors: - address: "a:27017" generation: 1 maxWireVersion: 9 when: "beforeHandshakeCompletes" type: "command" response: "{ok: 0, errmsg: "not primary"}" ``` -------------------------------- ### YAML Extended JSON Response Example Source: https://github.com/mongodb/mongo-csharp-driver/blob/main/specifications/server-discovery-and-monitoring/tests/README.rst Demonstrates how to represent an ObjectId in an extended JSON format within a hello response. ```yaml response: "{""$oid"": ""000000000000000000000002""}" ``` -------------------------------- ### Create and List Search Indexes Source: https://github.com/mongodb/mongo-csharp-driver/blob/main/specifications/index-management/tests/README.md Demonstrates the process of creating a search index and then listing it to verify its creation and properties. This is useful for testing the search index management capabilities of the driver. ```typescript { name: 'test-search-index', definition: { mappings: { dynamic: false } } } ``` -------------------------------- ### Type Query with GetType() Source: https://github.com/mongodb/mongo-csharp-driver/blob/main/Release Notes/Release Notes v1.5.md Example of performing a type query using the GetType() method on a property within a typed builder. ```csharp Query.Where(a => a.GetType() == typeof(T)) ``` -------------------------------- ### Build CSharpDriver Solution Source: https://github.com/mongodb/mongo-csharp-driver/blob/main/AGENTS.md Use this command to build the entire CSharpDriver solution. ```bash dotnet build CSharpDriver.sln ``` -------------------------------- ### Populating the Pool with a Connection Source: https://github.com/mongodb/mongo-csharp-driver/blob/main/specifications/connection-monitoring-and-pooling/connection-monitoring-and-pooling.rst This pseudocode details the process of preemptively creating and establishing connections to populate the pool, ensuring it meets the minimum size requirement without blocking application threads. Error handling is deferred to SDAM. ```pseudocode wait until pendingConnectionCount < maxConnecting and pool is "ready" create connection try: establish connection mark connection as available except error: # Defer error handling to SDAM. topology.handle_pre_handshake_error(error) ``` -------------------------------- ### Person Class Definition Source: https://github.com/mongodb/mongo-csharp-driver/blob/main/Release Notes/Release Notes v1.5.md Example Person class used to demonstrate typed builders. Attributes map C# properties to MongoDB fields. ```csharp public class Person { [BsonRepresentation(BsonType.ObjectId)] public string Id { get; set;} [BsonElement("fn")] public string FirstName { get; set;} [BsonElement("ln")] public string LastName { get; set;} [BsonElement("age")] public int Age { get; set;} } ``` -------------------------------- ### Establishing a Connection Source: https://github.com/mongodb/mongo-csharp-driver/blob/main/specifications/connection-monitoring-and-pooling/connection-monitoring-and-pooling.rst This pseudocode outlines the steps involved in establishing a new connection, including the initial handshake, handling compressed messages, and authentication. Errors during this process result in the connection being closed and the error being propagated. ```pseudocode try: connect connection via TCP / TLS perform connection handshake handle OP_COMPRESSED perform connection authentication emit ConnectionReadyEvent and equivalent log message return connection except error: close connection throw error # Propagate error in manner idiomatic to language. ``` -------------------------------- ### Marking a Connection as Available Source: https://github.com/mongodb/mongo-csharp-driver/blob/main/specifications/connection-monitoring-and-pooling/connection-monitoring-and-pooling.rst This pseudocode illustrates how a connection is marked as 'available' after it has been successfully established. It involves incrementing the available connection count and updating the connection's state. ```pseudocode increment availableConnectionCount set connection state to "available" add connection to availableConnections ``` -------------------------------- ### Run Benchmarks by Category Source: https://github.com/mongodb/mongo-csharp-driver/blob/main/benchmarks/MongoDB.Driver.Benchmarks/README.md Execute benchmarks belonging to a specific category, such as 'WriteBench'. The `--anyCategories` option selects benchmarks that match any of the provided categories. ```bash dotnet run -c Release -- --driverBenchmarks --anyCategories "WriteBench" ``` -------------------------------- ### Update a Search Index Definition Source: https://github.com/mongodb/mongo-csharp-driver/blob/main/specifications/index-management/tests/README.md Specifies the new definition for updating an existing search index. This example shows changing the dynamic mapping setting. ```typescript { name: 'test-search-index', definition: { mappings: { dynamic: true } } } ``` -------------------------------- ### Initialize C# Driver (Deprecated) Source: https://github.com/mongodb/mongo-csharp-driver/blob/main/Release Notes/Release Notes v1.7.md This is the older way to initialize the C# driver. It defaults to an Unacknowledged WriteConcern. Use MongoClient for new applications. ```csharp var connectionString = "mongodb://localhost"; var server = MongoServer.Create(connectionString); // deprecated var database = server.GetDatabase("test"); // WriteConcern defaulted to Unacknowledged ``` -------------------------------- ### Get Collection using GetCollection method Source: https://github.com/mongodb/mongo-csharp-driver/blob/main/Release Notes/Release Notes v1.8.md Use the GetCollection method with a type parameter to retrieve a collection instance. This replaces the deprecated indexer access. ```csharp var collection = database.GetCollection("test"); ``` -------------------------------- ### Advanced MongoClientSettings Configuration Source: https://context7.com/mongodb/mongo-csharp-driver/llms.txt Configure connection pooling, timeouts, compression, TLS, and Server API versions using MongoClientSettings. FromConnectionString is a common starting point. ```csharp var settings = MongoClientSettings.FromConnectionString( "mongodb+srv://user:pass@cluster0.example.mongodb.net/mydb"); // Override specific properties settings.MaxConnectionPoolSize = 200; settings.MinConnectionPoolSize = 10; settings.ConnectTimeout = TimeSpan.FromSeconds(10); settings.ServerSelectionTimeout = TimeSpan.FromSeconds(30); settings.SocketTimeout = TimeSpan.FromSeconds(60); settings.HeartbeatInterval = TimeSpan.FromSeconds(10); // Stable API — lock to a specific API version settings.ServerApi = new ServerApi(ServerApiVersion.V1, strict: false, deprecationErrors: false); // Compression settings.Compressors = new[] { new CompressorConfiguration(CompressorType.Snappy), new CompressorConfiguration(CompressorType.Zlib), new CompressorConfiguration(CompressorType.ZStandard) }; // TLS settings.SslSettings = new SslSettings { EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls13 }; // Logging (Microsoft.Extensions.Logging) settings.LoggingSettings = new LoggingSettings(loggerFactory); var client = new MongoClient(settings); ``` -------------------------------- ### Resume a Change Stream Source: https://context7.com/mongodb/mongo-csharp-driver/llms.txt Illustrates how to resume a change stream from a specific point using a resume token. This is crucial for ensuring no changes are missed if the application restarts. ```csharp // Resume a stream after a restart using a resume token BsonDocument resumeToken = null; using var cursor = await products.WatchAsync( new EmptyPipelineDefinition>(), new ChangeStreamOptions { ResumeAfter = resumeToken }); ``` -------------------------------- ### Get Database and Collection Source: https://context7.com/mongodb/mongo-csharp-driver/llms.txt Access a specific database using GetDatabase and then retrieve a typed or untyped collection using GetCollection. Custom collection settings can be applied. ```csharp using MongoDB.Bson; using MongoDB.Driver; // POCO model public class Product { public ObjectId Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } public string Category { get; set; } public int Stock { get; set; } } var client = new MongoClient("mongodb://localhost:27017"); var db = client.GetDatabase("shop"); // Typed collection var products = db.GetCollection("products"); // Untyped collection (BsonDocument) var rawCollection = db.GetCollection("events"); // Collection with custom settings var settings = new MongoCollectionSettings { ReadPreference = ReadPreference.Secondary, WriteConcern = WriteConcern.Acknowledged }; var auditLogs = db.GetCollection("audit_logs", settings); // List collections in the database var collectionNames = db.ListCollectionNames().ToList(); // Expected: ["products", "events", "audit_logs"] ``` -------------------------------- ### Create Multiple Search Indexes in Batch Source: https://github.com/mongodb/mongo-csharp-driver/blob/main/specifications/index-management/tests/README.md Demonstrates how to create multiple search indexes on a collection in a single batch operation. Ensure the collection exists before creating indexes. ```typescript { name: 'test-search-index-1', definition: { mappings: { dynamic: false } } } ``` ```typescript { name: 'test-search-index-2', definition: { mappings: { dynamic: false } } } ```