### Get Guitar Collection Reference Source: https://www.mongodb.com/docs/drivers/csharp/current/crud/query/query-filter Establishes a connection to the 'guitars' collection in the 'example' database. ```csharp var client = new MongoClient("localhost://27017"); var guitarCollection = client.GetDatabase("example").GetCollection("guitars"); ``` -------------------------------- ### Example GUID Source: https://www.mongodb.com/docs/drivers/csharp/current/serialization/guids A standard example of a GUID format. ```plaintext 00112233-4455-6677-8899-aabbccddeeff ``` -------------------------------- ### Connection URI Example for Read Preference Source: https://www.mongodb.com/docs/drivers/csharp/current/connect/connection-options/server-selection Example of configuring read preference, max staleness, and read preference tags in a MongoDB connection URI. ```none readPreference=primaryPreferred &maxStalenessSeconds=90 &readPreferenceTags=dc:ny,rack:1 ``` -------------------------------- ### Add MongoDB.Driver.Authentication.AWS NuGet Package Source: https://www.mongodb.com/docs/drivers/csharp/current/security/authentication/aws-iam Install the AWS authentication package using the .NET CLI. ```bash dotnet add package MongoDB.Driver.Authentication.AWS ``` -------------------------------- ### Run the Application Source: https://www.mongodb.com/docs/drivers/csharp/current/integrations/odata Execute the application from your project's root directory using the dotnet CLI. This command starts the OData service. ```shell dotnet run ODataExample.csproj ``` -------------------------------- ### Example Output of Find Operation Source: https://www.mongodb.com/docs/drivers/csharp/current/crud/query/find This is an example of the output produced by the find operation. ```text Pizza Town Victoria Pizza ... ``` -------------------------------- ### Server Selection Timeout Exception Example Source: https://www.mongodb.com/docs/drivers/csharp/current/connect/connection-options/server-selection This is an example of a server selection timeout exception. Analyze the cluster state and heartbeat exceptions to diagnose issues. ```none A timeout occurred after 30000ms selecting a server using CompositeServerSelector{ Selectors = MongoDB.Driver.MongoClient+AreSessionsSupportedServerSelector, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 }, OperationsCountServerSelector }. Client view of cluster state is { ClusterId : "1", Type : "Unknown", State : "Disconnected", Servers : [{ ServerId: "{ ClusterId : 1, EndPoint : "Unspecified/localhost:27017" }", EndPoint: "Unspecified/localhost:27017", ReasonChanged: "Heartbeat", State: "Disconnected", ServerVersion: , TopologyVersion: , Type: "Unknown", HeartbeatException: "" }] }. ``` -------------------------------- ### Example Document with Pagination Token Source: https://www.mongodb.com/docs/drivers/csharp/current/crud/query/project An example of a document returned with a `paginationToken` when using `MetaSearchSequenceToken`. ```json { "_id": { "$oid": "573a13def29313caabdb5661" }, "plot": "She Can See Her Future, But Can't Escape Her Past.", "title": "West", "paginationToken": "CIeaARWv2zRAIg5aDFc6E97ykxPKq9tWYQ==" } ``` -------------------------------- ### Example Time Series Collection Output Source: https://www.mongodb.com/docs/drivers/csharp/current/time-series This is an example of the output from `ListCollections()` for a time series collection, showing its name, type, and options. ```json { "name": "september2021", "type": "timeseries", "options": { "timeseries": { "timeField": "temperature", "granularity": "seconds", "bucketMaxSpanSeconds": 3600 } }, "info": { "readOnly": false } } ... ``` -------------------------------- ### Create MongoClient with Connection URI Source: https://www.mongodb.com/docs/drivers/csharp/current/connect/mongoclient Instantiate a MongoClient by passing a connection URI to its constructor. This example connects to a MongoDB deployment running on localhost:27017. ```csharp const string uri = "mongodb://localhost:27017/"; var client = new MongoClient(uri); ``` -------------------------------- ### Add MongoDB.AspNetCore.OData NuGet Package Source: https://www.mongodb.com/docs/drivers/csharp/current/integrations/odata Install the OData integration package for the .NET/C# Driver using the .NET CLI. ```shell dotnet add package MongoDB.AspNetCore.OData ``` -------------------------------- ### Run ASP.NET Core Application Source: https://www.mongodb.com/docs/drivers/csharp-frameworks/ef-odata Compiles and starts the ASP.NET Core OData REST API. Ensure your MongoDB connection string is correctly configured in appsettings.json. ```bash dotnet run ``` -------------------------------- ### Example Connection Error Message Source: https://www.mongodb.com/docs/drivers/csharp/current/connect/connection-troubleshooting This message indicates the driver cannot connect to the specified MongoDB server hostname or port. ```none Error: couldn't connect to server 127.0.0.1:27017 ``` -------------------------------- ### Start MongoDB Session with Custom ClientSessionOptions Source: https://www.mongodb.com/docs/drivers/csharp/current/crud/transactions Use custom ClientSessionOptions to configure causal consistency and default transaction settings when starting a new client session. Ensure the MongoDB server is running on localhost:27017. ```csharp var client = new MongoClient("mongodb://localhost:27017"); var sessionOptions = new ClientSessionOptions { CausalConsistency = true, DefaultTransactionOptions = new TransactionOptions( readConcern: ReadConcern.Available, writeConcern: WriteConcern.Acknowledged) }; var session = client.StartSession(sessionOptions); ``` -------------------------------- ### Example Authentication Failed Error Source: https://www.mongodb.com/docs/drivers/csharp/current/connect/connection-troubleshooting This message indicates an authentication failure, often due to incorrect credentials or mechanism configuration. ```none Command failed with error 18 (AuthenticationFailed): 'Authentication failed.' on server :. ``` ```none Authentication failed","attr":{"mechanism":"SCRAM-SHA-256","principalName": "","":"","client":"127.0.0.1:2012", "result":"UserNotFound: Could not find user}} ``` ```none connection() error occurred during connection handshake: auth error: sasl conversation error: unable to authenticate using mechanism "SCRAM-SHA-256": (AuthenticationFailed) Authentication failed. ``` -------------------------------- ### Find Documents with Options Source: https://www.mongodb.com/docs/drivers/csharp/current/crud/query/find This example demonstrates how to find documents matching a specific filter and configure find options like BatchSize. It retrieves results into a cursor and iterates through them. ```APIDOC ## Find() with Options ### Description Finds documents in a collection that match a specified filter and applies optional configurations like batch size. The results are returned as a cursor. ### Method `IMongoCollection.Find(FilterDefinition, FindOptions)` ### Endpoint N/A (This is an SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp var filter = Builders.Filter.Eq("cuisine", "Pizza"); var findOptions = new FindOptions { BatchSize = 3 }; using (var cursor = _restaurantsCollection.Find(filter, findOptions).ToCursor()) { foreach (var r in cursor.ToEnumerable()) { WriteLine(r.Name); } } ``` ### Response #### Success Response (Cursor) Returns an `IAsyncCursor` which can be iterated to retrieve documents. #### Response Example ``` Pizza Town Victoria Pizza ... ``` ### Additional Information - The `using` statement ensures `Dispose()` is called on the cursor. - Refer to the [API Documentation](https://mongodb.github.io/mongo-csharp-driver/3.8.0/api/MongoDB.Driver/MongoDB.Driver.IMongoCollectionExtensions.Find.html) for `Find()`. - Refer to the [API Documentation](https://mongodb.github.io/mongo-csharp-driver/3.8.0/api/MongoDB.Driver/MongoDB.Driver.FindOptions.html) for `FindOptions`. ``` -------------------------------- ### Initialize MongoDB Service Source: https://www.mongodb.com/docs/drivers/csharp/current/crud/restful-api-tutorial Initializes the MongoDBService class, establishing a connection to the MongoDB database and getting the specified collection. ```csharp using MongoExample.Models; using Microsoft.Extensions.Options; using MongoDB.Driver; using MongoDB.Bson; namespace MongoExample.Services; public class MongoDBService { private readonly IMongoCollection _playlistCollection; public MongoDBService(IOptions mongoDBSettings) { MongoClient client = new MongoClient(mongoDBSettings.Value.ConnectionURI); IMongoDatabase database = client.GetDatabase(mongoDBSettings.Value.DatabaseName); _playlistCollection = database.GetCollection(mongoDBSettings.Value.CollectionName); } public async Task> GetAsync() { } public async Task CreateAsync(Playlist playlist) { } public async Task AddToPlaylistAsync(string id, string movieId) {} public async Task DeleteAsync(string id) { } } ``` -------------------------------- ### Start a New Session Source: https://www.mongodb.com/docs/drivers/csharp/current/crud/transactions Create a new session from a MongoClient instance. It is recommended to reuse the client for multiple sessions and transactions. ```csharp var client = new MongoClient("mongodb://localhost:27017"); var session = client.StartSession(); ``` -------------------------------- ### Create InsertOneModel for Bulk Write Source: https://www.mongodb.com/docs/drivers/csharp/current/crud/bulk-write Instantiate an `InsertOneModel` to specify a single document for insertion within a bulk write operation. This example targets the 'restaurants' collection. ```csharp var insertOneModel = new InsertOneModel( new BsonDocument{ { "name", "Mongo's Deli" }, { "cuisine", "Sandwiches" }, { "borough", "Manhattan" }, { "restaurant_id", "1234" } } ); ``` -------------------------------- ### StartTransactionAsync Source: https://www.mongodb.com/docs/drivers/csharp/current/crud/transactions Starts a transaction on the current session and executes a given callback function. It allows for customization of transaction behavior using TransactionOptions. ```APIDOC ## StartTransactionAsync ### Description Starts a transaction on this session and runs the given callback. To learn more about this method, see the [withTransaction() page](https://www.mongodb.com/docs/manual/reference/method/Session.withTransaction/#std-label-session-withTransaction) in the Server manual. IMPORTANT: When catching exceptions within the callback function used by `WithTransactionAsync()`, you **must** rethrow the exception before exiting the try-catch block. Failing to do so can result in an infinite loop. For further details on how to handle exceptions in this case, see [Transactions](https://www.mongodb.com/docs/manual/core/transactions/#std-label-transactions) in the Server manual and select C# from the language dropdown to view the example. ### Parameters - **callback** (Func>) - Required - The asynchronous callback function to execute within the transaction. - **options** (TransactionOptions) - Optional - Customizes the behavior of the transaction, overriding default transaction options. - **cancellationToken** (CancellationToken) - Optional - Propagates notification that operations should be canceled. ### Return Type - **Task** - A task that represents the asynchronous operation, returning the result of the callback function. ### Customizing Transaction Behavior You can customize the behavior of individual transactions by passing an instance of the `TransactionOptions` class to the `StartTransaction()` or `WithTransaction()` method. The options that you set here override the default transaction options that you set on the `ClientSessionOptions` object. ``` -------------------------------- ### Implement IOidcCallback Interface Source: https://www.mongodb.com/docs/drivers/csharp/current/security/authentication/oidc Define a class that implements the IOidcCallback interface to retrieve OIDC access tokens. This example reads the token from a local file. ```csharp public class MyCallback : IOidcCallback { public OidcAccessToken GetOidcAccessToken( OidcCallbackParameters parameters, CancellationToken cancellationToken) { var accessToken = File.ReadAllText("access-token.dat"); return new(accessToken, expiresIn: null); } public async Task GetOidcAccessTokenAsync( OidcCallbackParameters parameters, CancellationToken cancellationToken) { var accessToken = await File.ReadAllTextAsync( "access-token.dat", cancellationToken) .ConfigureAwait(false); return new(accessToken, expiresIn: null); } } ``` -------------------------------- ### Find Files Synchronously Source: https://www.mongodb.com/docs/drivers/csharp/current/crud/gridfs This example demonstrates how to find files in a GridFS bucket synchronously using the Find() method and iterate through the results. ```APIDOC ## Find Files Synchronously ### Description Finds files in a GridFS bucket synchronously. ### Method `GridFSBucket.Find()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp var filter = Builders.Filter.Empty; var files = bucket.Find(filter); foreach (var file in files.ToEnumerable()) { Console.WriteLine(file.ToJson()); } ``` ### Response #### Success Response (200) Returns an `IAsyncCursor` instance containing the found files. #### Response Example ```json { "_id" : { "$oid" : "..." }, "length" : 13, "chunkSize" : 261120, "uploadDate" : { "$date" : ... }, "filename" : "new_file" } { "_id" : { "$oid" : "..." }, "length" : 50, "chunkSize" : 1048576, "uploadDate" : { "$date" : ... }, "filename" : "my_file" } ``` ``` -------------------------------- ### Find Files Asynchronously Source: https://www.mongodb.com/docs/drivers/csharp/current/crud/gridfs This example demonstrates how to find files in a GridFS bucket asynchronously using the FindAsync() method and process the results. ```APIDOC ## Find Files Asynchronously ### Description Finds files in a GridFS bucket asynchronously. ### Method `GridFSBucket.FindAsync()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp var filter = Builders.Filter.Empty; var files = await bucket.FindAsync(filter); await files.ForEachAsync(file => Console.Out.WriteLineAsync(file.ToJson())) ``` ### Response #### Success Response (200) Returns an `IAsyncCursor` instance containing the found files. #### Response Example ```json { "_id" : { "$oid" : "..." }, "length" : 13, "chunkSize" : 261120, "uploadDate" : { "$date" : ... }, "filename" : "new_file" } { "_id" : { "$oid" : "..." }, "length" : 50, "chunkSize" : 1048576, "uploadDate" : { "$date" : ... }, "filename" : "my_file" } ``` ``` -------------------------------- ### Create New Web API Project Source: https://www.mongodb.com/docs/drivers/csharp/current/crud/restful-api-tutorial Creates a new .NET Core web application project named MongoExample. ```bash dotnet new webapi -o MongoExample cd MongoExample ``` -------------------------------- ### Create a new .NET Console Project Source: https://www.mongodb.com/docs/drivers/csharp/current/get-started Use these bash commands to create a new directory and initialize a .NET console application. This sets up the basic project structure. ```bash mkdir csharp-quickstart cd csharp-quickstart dotnet new console ``` -------------------------------- ### Open and Read from GridFS Download Stream (Synchronous) Source: https://www.mongodb.com/docs/drivers/csharp/current/crud/gridfs Use `OpenDownloadStream()` to get a readable stream for a GridFS file. This example finds a file by its filename and then reads its entire content into a byte buffer. ```csharp var filter = Builders.Filter.Eq(x => x.Filename, "new_file"); var doc = bucket.Find(filter).FirstOrDefault(); if (doc != null) { using (var downloader = bucket.OpenDownloadStream(doc.Id)) { var buffer = new byte[downloader.Length]; downloader.Read(buffer, 0, buffer.Length); // Process the buffer as needed } } ``` -------------------------------- ### Run the 'hello' Command (Synchronous) Source: https://www.mongodb.com/docs/drivers/csharp/current/run-command Execute the 'hello' database command synchronously. This command returns information about the server. Use this when asynchronous operations are not required. ```csharp var command = new BsonDocument("hello", 1); var result = database.RunCommand(command); ``` -------------------------------- ### Watch and Split Large Change Events (Asynchronous) Source: https://www.mongodb.com/docs/drivers/csharp/current/logging-and-monitoring/change-streams This asynchronous example watches for changes and splits events exceeding 16 MB. It utilizes the ChangeStreamSplitLargeEvent() method and requires an asynchronous collection setup. ```csharp var pipeline = new EmptyPipelineDefinition>() .ChangeStreamSplitLargeEvent(); using var cursor = await collection.WatchAsync(pipeline); await foreach (var completeEvent in GetNextChangeStreamEventAsync(cursor)) { Console.WriteLine("Received the following change: " + completeEvent.BackingDocument); } ``` -------------------------------- ### Open and Read from GridFS Download Stream (Asynchronous) Source: https://www.mongodb.com/docs/drivers/csharp/current/crud/gridfs Use `OpenDownloadStreamAsync()` to asynchronously get a readable stream for a GridFS file. This example finds a file by its filename and then reads its entire content into a byte buffer. ```csharp var filter = Builders.Filter.Eq(x => x.Filename, "new_file"); var cursor = await bucket.FindAsync(filter); var fileInfoList = await cursor.ToListAsync(); var doc = fileInfoList.FirstOrDefault(); if (doc != null) { using (var downloader = await bucket.OpenDownloadStreamAsync(doc.Id)) { var buffer = new byte[downloader.Length]; await downloader.ReadAsync(buffer, 0, buffer.Length); // Process the buffer as needed } } ``` -------------------------------- ### Create ASP.NET Core Web API Project Source: https://www.mongodb.com/docs/drivers/csharp-frameworks/ef-odata Use the .NET CLI to create a new ASP.NET Core Web API project. Navigate into the project directory. ```bash dotnet new webapi -n RestaurantODataApi cd RestaurantODataApi ``` -------------------------------- ### Filter Documents by Field Value Pattern Source: https://www.mongodb.com/docs/drivers/csharp/current/crud/query/query-filter Use the Regex() method to create a filter that matches documents where a specified field's value matches a regular expression. This example finds documents where the 'make' field starts with 'G'. ```csharp // Creates a filter for all documents with a populated "ratings" field var filter = Builders.Filter.Regex(g => g.Make, "^G"); // Finds all documents that match the filter var result = guitarCollection.Find(filter).ToList(); foreach (var doc in result) { // Prints the documents in bson (json) format Console.WriteLine(doc.ToBsonDocument()); } ``` ```json { "_id" : 2, "make" : "Gibson", "models" : ["Les Paul", "SG", "Explorer"], "establishedYear" : 1902, "rating" : 8 } ``` -------------------------------- ### Create ObjectSerializer with GUID Representation Source: https://www.mongodb.com/docs/drivers/csharp/current/serialization/guids Construct an `ObjectSerializer` and specify the desired GUID representation. This is useful when serializing hierarchical objects containing GUIDs. ```csharp var objectDiscriminatorConvention = BsonSerializer.LookupDiscriminatorConvention(typeof(object)); var objectSerializer = new ObjectSerializer(objectDiscriminatorConvention, GuidRepresentation.Standard); ``` -------------------------------- ### Run the 'hello' Command (Asynchronous) Source: https://www.mongodb.com/docs/drivers/csharp/current/run-command Execute the 'hello' database command asynchronously. This command returns information about the server. Use this for non-blocking operations in your application. ```csharp var command = new BsonDocument("hello", 1); var result = await database.RunCommandAsync(command); ``` -------------------------------- ### Open Download Stream with Options (Synchronous) Source: https://www.mongodb.com/docs/drivers/csharp/current/crud/gridfs Demonstrates how to open a synchronous download stream with custom options, such as enabling seeking. ```APIDOC ## OpenDownloadStream with Options ### Description Opens a synchronous download stream for a GridFS file with specified options. ### Method `bucket.OpenDownloadStream(id, options)` ### Parameters #### Path Parameters - **id** (BsonValue) - Required - The `_id` value of the file to download. #### Query Parameters None #### Request Body - **options** (GridFSDownloadOptions) - Optional - An instance of `GridFSDownloadOptions` to configure the download stream. Defaults to null. - **Seekable** (bool?) - Optional - Indicates whether the stream supports seeking. Defaults to false. ### Request Example ```csharp var filter = Builders.Filter.Eq(x => x.Filename, "new_file"); var doc = bucket.Find(filter).FirstOrDefault(); if (doc != null) { var options = new GridFSDownloadOptions { Seekable = true }; using (var downloader = bucket.OpenDownloadStream(doc.Id, options)) { var buffer = new byte[downloader.Length]; downloader.Read(buffer, 0, buffer.Length); // Process the buffer as needed } } ``` ### Response #### Success Response (Stream) Returns a readable stream for the GridFS file. #### Response Example (Stream content) ``` -------------------------------- ### Serialize GUID IDs with Standard Representation Source: https://www.mongodb.com/docs/drivers/csharp/current/serialization/class-mapping Specify `GuidRepresentation.Standard` when initializing `GuidSerializer` to control how GUID values are serialized. ```csharp BsonClassMap.RegisterClassMap(classMap => { classMap.AutoMap(); classMap.IdMemberMap.SetSerializer(new GuidSerializer(GuidRepresentation.Standard)); }); ``` -------------------------------- ### Open Download Stream with Options (Asynchronous) Source: https://www.mongodb.com/docs/drivers/csharp/current/crud/gridfs Demonstrates how to open an asynchronous download stream with custom options, such as enabling seeking. ```APIDOC ## OpenDownloadStreamAsync with Options ### Description Opens an asynchronous download stream for a GridFS file with specified options. ### Method `await bucket.OpenDownloadStreamAsync(id, options)` ### Parameters #### Path Parameters - **id** (BsonValue) - Required - The `_id` value of the file to download. #### Query Parameters None #### Request Body - **options** (GridFSDownloadOptions) - Optional - An instance of `GridFSDownloadOptions` to configure the download stream. Defaults to null. - **Seekable** (bool?) - Optional - Indicates whether the stream supports seeking. Defaults to false. ### Request Example ```csharp var filter = Builders.Filter.Eq(x => x.Filename, "new_file"); var cursor = await bucket.FindAsync(filter); var fileInfoList = await cursor.ToListAsync(); var doc = fileInfoList.FirstOrDefault(); if (doc != null) { var options = new GridFSDownloadOptions { Seekable = true }; using (var downloader = await bucket.OpenDownloadStreamAsync(doc.Id, options)) { var buffer = new byte[downloader.Length]; await downloader.ReadAsync(buffer, 0, buffer.Length); // Process the buffer as needed } } ``` ### Response #### Success Response (Stream) Returns a readable stream for the GridFS file. #### Response Example (Stream content) ``` -------------------------------- ### Example Canonical Extended JSON Output Source: https://www.mongodb.com/docs/drivers/csharp/current/document-formats/extended-json This is an example of the Canonical Extended JSON output generated from the `MyDocument` class. ```json { "_id" : { "$oid" : "68094769744af81f368ff1c1" }, "CreatedAt" : { "$date" : { "$numberLong" : "1745438569994" } }, "NumViews" : { "$numberLong" : "1234567890" } } ``` -------------------------------- ### Construct Legacy GUID for Query Filter Source: https://www.mongodb.com/docs/drivers/csharp/current/serialization/guids To construct legacy (subtype 3) GUID values, use the BsonBinaryData() constructor with GuidRepresentation.CSharpLegacy. ```csharp var guid = new Guid("00112233-4455-6677-8899-aabbccddeeff"); var legacyGuid = new BsonBinaryData(guid, GuidRepresentation.CSharpLegacy); var filter = new BsonDocument("legacyGuidField", legacyGuid); ``` -------------------------------- ### Configure X.509 Authentication via Connection String Source: https://www.mongodb.com/docs/drivers/csharp/current/security/authentication/x509 Configure TLS and provide X.509 client certificates using a connection string. Ensure to set `UseTls` to true and configure `SslSettings.ClientCertificates`. ```csharp var connectionString = "mongodb[+srv]://[:]/?authSource=$external&authMechanism=MONGODB-X509"; var settings = MongoClientSettings.FromConnectionString(connectionString); settings.UseTls = true; settings.SslSettings = new SslSettings { ClientCertificates = new List() { new X509Certificate2("", "") } }; ``` -------------------------------- ### Sample Documents using LINQ Source: https://www.mongodb.com/docs/drivers/csharp/current/aggregation/linq Use the `Sample` method on an aggregation pipeline to retrieve a random subset of documents from a collection. ```csharp var query = queryableCollection .Aggregate() .Sample(4) .ToList(); ``` -------------------------------- ### Default GuidGenerator for Guid ID Source: https://www.mongodb.com/docs/drivers/csharp/current/serialization/poco When no specific ID generator attribute is applied, the driver automatically uses `GuidGenerator` for `Guid` ID properties. ```csharp public class House { public Guid Id { get; set; } } ``` -------------------------------- ### Example Search Result Document Source: https://www.mongodb.com/docs/drivers/csharp/current/atlas-search This is an example of a document that might be returned from a MongoDB Search operation, including metadata like _id and title. ```json { "_id" : ObjectId("..."), "title" : "About Time", "plot" : "...", "genres" : ["Comedy", "Drama", "Romance"], "year" : 2013, "rated" : "R", "imdb" : { "rating" : 7.8, "votes" : "...", "id" : "..." } } ``` -------------------------------- ### Read Data with GET Endpoint Source: https://www.mongodb.com/docs/drivers/csharp/current/crud/restful-api-tutorial Implement the GetAsync function in MongoDBService.cs to retrieve all documents from the playlist collection. This is used by the GET endpoint in PlaylistController.cs. ```csharp public async Task> GetAsync() { return await _playlistCollection.Find(new BsonDocument()).ToListAsync(); } ``` ```csharp [HttpGet] public async Task> Get() { return await _mongoDBService.GetAsync(); } ``` -------------------------------- ### Configure MongoDB Service in Program.cs Source: https://www.mongodb.com/docs/drivers/csharp/current/crud/restful-api-tutorial Add MongoDB settings and register the MongoDB service with dependency injection in your application's startup file. ```csharp using MongoExample.Models; using MongoExample.Services; var builder = WebApplication.CreateBuilder(args); builder.Services.Configure(builder.Configuration.GetSection("MongoDB")); builder.Services.AddSingleton(); ``` -------------------------------- ### Enable Client-Side Projections with Project() Source: https://www.mongodb.com/docs/drivers/csharp/current/reference/release-notes Illustrates enabling client-side projection for the Project() aggregation stage. This provides control over the shape of the output documents in an aggregation pipeline. ```csharp // Enable client-side projection var aggregateOptions = new AggregateOptions(); aggregateOptions.TranslationOptions = new ExpressionTranslationOptions { EnableClientSideProjections = true }; var aggregate = collection .Aggregate(aggregateOptions) .Project(doc => new { R = MyFunction(doc.Name) }); ``` -------------------------------- ### Specify CombGuidGenerator for Guid ID Source: https://www.mongodb.com/docs/drivers/csharp/current/serialization/poco Apply the `[BsonId(IdGenerator = typeof(CombGuidGenerator))]` attribute to use the COMB algorithm for generating unique `Guid` values. ```csharp public class House { [BsonId(IdGenerator = typeof(CombGuidGenerator))] public Guid Id { get; set; } } ``` -------------------------------- ### Specify GUID Representation with Attribute Source: https://www.mongodb.com/docs/drivers/csharp/current/serialization/guids Use the `BsonGuidRepresentation` attribute on a GUID property to specify its BSON representation. This attribute accepts a value from the `GuidRepresentation` enum. ```csharp public class Widget { public int Id { get; set; } [BsonGuidRepresentation(GuidRepresentation.Standard)] public Guid G { get; set; } } ``` -------------------------------- ### Equality Filter with Method and Alternative Syntax Source: https://www.mongodb.com/docs/drivers/csharp/current/crud/query/query-filter Demonstrates how to use the Eq method and its alternative syntax for filtering documents. ```csharp var filter = Builders.Filter.Eq(g => g.Make, "Fender"); var results = guitarCollection.Find(filter).ToList(); // Alternative syntax var results = guitarCollection.Find(g => g.Make == "Fender").ToList();; ``` -------------------------------- ### GUID Encoding Differences (Subtype 3) Source: https://www.mongodb.com/docs/drivers/csharp/current/serialization/guids Different drivers may encode GUIDs with varying byte orders when using BsonBinaryData subtype 3. ```plaintext 33221100-5544-7766-8899-aabbccddeeff ``` ```plaintext 00112233-4455-6677-8899-aabbccddeeff ``` ```plaintext 77665544-3322-1100-ffee-ddccbbaa9988 ``` -------------------------------- ### Create a Default GridFS Bucket Source: https://www.mongodb.com/docs/drivers/csharp/current/crud/gridfs Instantiate a GridFSBucket to interact with the default 'fs' bucket. This creates the bucket if it doesn't exist. ```csharp var client = new MongoClient(""); var database = client.GetDatabase("db"); // Creates a GridFS bucket or references an existing one var bucket = new GridFSBucket(database); ``` -------------------------------- ### Define Student Class for Array Example Source: https://www.mongodb.com/docs/drivers/csharp/current/aggregation/linq A sample C# class definition to model documents containing an array field, used in the `TakeWhile` example. ```csharp public class Student { public ObjectId Id { get; set; } public string Name { get; set; } public int[] Grades { get; set; } } ``` -------------------------------- ### Create and Commit a Transaction in C# Source: https://www.mongodb.com/docs/drivers/csharp/current/crud/transactions Use this snippet to start a session, configure transaction options, insert documents into multiple collections, and commit the transaction. Ensure you handle potential exceptions. ```csharp var books = database.GetCollection("books"); var films = database.GetCollection("films"); // Begins transaction using (var session = mongoClient.StartSession()) { // Configures transaction options var transactionOptions = new TransactionOptions( readConcern: ReadConcern.Majority, writeConcern: WriteConcern.WMajority ); session.StartTransaction(transactionOptions); try { // Creates sample data var book = new Book { Title = "Beloved", Author = "Toni Morrison", InStock = true }; var film = new Film { Title = "Star Wars", Director = "George Lucas", InStock = true }; // Inserts sample data books.InsertOne(session, book); films.InsertOne(session, film); // Commits our transaction session.CommitTransaction(); } catch (Exception e) { Console.WriteLine("Error writing to MongoDB: " + e.Message); return; } // Prints a success message if no error thrown Console.WriteLine("Successfully committed transaction!"); } ``` -------------------------------- ### OData Query Result Example Source: https://www.mongodb.com/docs/drivers/csharp/current/integrations/odata A successful OData query to the /odata/Restaurants endpoint returns a JSON array of restaurant documents. This example shows the structure of the returned data. ```json { "@odata.context": "http://localhost:5183/odata/$metadata#Restaurants", "value": [ { "Name": "Glorious Food", "RestaurantId": "40361521", "Cuisine": "American", "Borough": "Manhattan", "Id": "...", "Address": { "Building": "522", "Coordinates": [-73.95171, 40.767461], "Street": "East 74 Street", "ZipCode": "10021" }, "Grades": [ ... ] }, ... ] } ``` -------------------------------- ### Configure OData Service in Program.cs Source: https://www.mongodb.com/docs/drivers/csharp/current/integrations/odata Configure the OData service and map controller endpoints in your Program.cs file. This includes setting up the MongoDB client, defining the OData model, and registering OData services with query capabilities. ```csharp using Microsoft.AspNetCore.OData; using Microsoft.OData.ModelBuilder; using MongoDB.Bson.Serialization.Conventions; using MongoDB.Driver; using ODataTest.Models; var builder = WebApplication.CreateBuilder(args); // Registers a convention pack to convert fields to camel case var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() }; ConventionRegistry.Register( "CamelCase", camelCaseConvention, type => true); builder.Services.AddSingleton( new MongoClient("")); // Registers the Restaurants entity and sets the Id field as the key var modelBuilder = new ODataConventionModelBuilder(); modelBuilder.EntitySet("Restaurants"); modelBuilder.EntityType().HasKey(r => r.Id); // Adds OData and specify query capabilities builder.Services.AddControllers().AddOData( options => options.Select() .AddRouteComponents("odata", modelBuilder.GetEdmModel()) ); var app = builder.Build(); app.UseRouting(); app.MapControllers(); app.Run(); ``` -------------------------------- ### Create Plain Credential Source: https://www.mongodb.com/docs/drivers/csharp/current/connect/connection-options Use this to create a plain credential for authentication. Specify the database, username, and password. ```csharp var settings = new MongoClientSettings { Credential = MongoCredential.CreatePlainCredential( databaseName: "admin", username: "user", password: "password" ) }; ``` -------------------------------- ### Set Username and Password Source: https://www.mongodb.com/docs/drivers/csharp/current/connect/connection-options Configure the username and password for authentication. This is a common way to provide credentials. ```csharp var builder = new MongoUrlBuilder { Username = "user", Password = "password" }; ``` -------------------------------- ### Extended JSON Example - Relaxed Source: https://www.mongodb.com/docs/drivers/csharp/current/document-formats/extended-json Represents BSON documents with some type information loss, prioritizing human-readability and interoperability. ```json { "_id": { "$oid": "573a1391f29313caabcd9637" }, "createdAt": { "$date": "2020-09-30T18:22:51.648Z" }, "numViews": 36520312 } ``` -------------------------------- ### BulkWriteAsync with BulkWriteOptions Source: https://www.mongodb.com/docs/drivers/csharp/current/crud/bulk-write Demonstrates how to perform an unordered bulk write operation asynchronously using BulkWriteOptions. ```APIDOC ## BulkWriteAsync with BulkWriteOptions ### Description Performs a bulk write operation asynchronously, allowing for customization of operation behavior through `BulkWriteOptions`. ### Method `Task BulkWriteAsync(IEnumerable> models, BulkWriteOptions options = null, CancellationToken cancellationToken = default(CancellationToken))`` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **models** (IEnumerable>) - Required - A list of write models to be executed in the bulk operation. - **options** (BulkWriteOptions) - Optional - An object that specifies options for the bulk write operation. - **BypassDocumentValidation** (bool) - Optional - Specifies whether the operation bypasses document-level validation. Defaults to `False`. - **Comment** (BsonValue) - Optional - A comment to attach to the operation. - **IsOrdered** (bool) - Optional - If `True`, operations are performed in order and stop on error. If `False`, operations are performed in arbitrary order, and all attempt to complete. Defaults to `True`. - **Let** (BsonDocument) - Optional - A map of parameter names and values for the operation. - **cancellationToken** (CancellationToken) - Optional - A token to monitor for cancellation requests. ### Request Example ```csharp var models = new List> { new DeleteOneModel( Builders.Filter.Eq("restaurant_id", "5678") ) }; var options = new BulkWriteOptions { IsOrdered = false }; await collection.BulkWriteAsync(models, options); ``` ### Response #### Success Response (200) - **BulkWriteResult** - An object containing the results of the bulk write operation. - **IsAcknowledged** (bool) - Indicates whether the server acknowledged the operation. - **DeletedCount** (long?) - The number of documents deleted. - **InsertedCount** (long?) - The number of documents inserted. - **MatchedCount** (long?) - The number of documents matched for an update. - **ModifiedCount** (long?) - The number of documents modified. - **IsModifiedCountAvailable** (bool) - Indicates whether the modified count is available. - **Upserts** (IReadOnlyList) - A list of upsert operations. - **RequestCount** (int) - The number of requests in the bulk operation. #### Response Example ```json { "IsAcknowledged": true, "DeletedCount": 1, "InsertedCount": 0, "MatchedCount": 0, "ModifiedCount": 0, "IsModifiedCountAvailable": false, "Upserts": [], "RequestCount": 1 } ``` ### Handling Exceptions - **BulkWriteError**: Thrown if any operation in the bulk write fails. The driver stops further operations. - **BulkWriteError.Index**: The index of the request that resulted in an error. ``` -------------------------------- ### BsonIgnoreIfDefault Attribute Example Source: https://www.mongodb.com/docs/drivers/csharp/current/crud/replace Illustrates how to use the `[BsonIgnoreIfDefault]` attribute on the `_id` field for POCOs when the `_id` is of type `ObjectId`. ```csharp public class Restaurant { [BsonIgnoreIfDefault] public ObjectId Id { get; set; } // Other properties } ``` -------------------------------- ### Create OData Controller for Restaurants Source: https://www.mongodb.com/docs/drivers/csharp/current/integrations/odata Sets up an ASP.NET Core OData controller to expose restaurant data from MongoDB. It connects to the 'sample_restaurants' database and the 'restaurants' collection, enabling OData querying with a page size of 5. ```csharp using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.OData.Routing.Controllers; using MongoDB.AspNetCore.OData; using MongoDB.Driver; using ODataTest.Models; namespace ODataTest.Controllers; public class RestaurantsController : ODataController { private readonly IQueryable _restaurants; public RestaurantsController(IMongoClient client) { var database = client.GetDatabase("sample_restaurants"); _restaurants = database.GetCollection("restaurants") .AsQueryable(); } // Registers Get endpoint and sets max documents to 5 [MongoEnableQuery(PageSize = 5)] public ActionResult> Get() { return Ok(_restaurants); } } ``` -------------------------------- ### Connect with GSSAPI via Connection String Source: https://www.mongodb.com/docs/drivers/csharp/current/security/authentication/kerberos Use this connection string to authenticate with GSSAPI. Replace placeholders with your actual credentials and host information. ```csharp var mongoClient = new MongoClient("mongodb://:@[:]/?authMechanism=GSSAPI"); ``` -------------------------------- ### Enable Compression via MongoClientSettings Source: https://www.mongodb.com/docs/drivers/csharp/current/connect/connection-options/network-compression Configure compression by setting the 'Compressors' property in MongoClientSettings. Provide a list of CompressorConfiguration objects, each specifying a CompressorType. ```csharp var settings = new MongoClientSettings() { Scheme = ConnectionStringScheme.MongoDB, Server = new MongoServerAddress(""), Compressors = new List() { new CompressorConfiguration(CompressorType.Snappy), new CompressorConfiguration(CompressorType.Zlib), new CompressorConfiguration(CompressorType.Zstandard) } }; var client = new MongoClient(settings); ``` -------------------------------- ### OpenUploadStream with Options Source: https://www.mongodb.com/docs/drivers/csharp/current/crud/gridfs Demonstrates how to use `OpenUploadStream` or `OpenUploadStreamAsync` with custom `GridFSUploadOptions`. ```APIDOC ## OpenUploadStream with Options ### Description Uploads a file to GridFS using custom upload options, such as specifying the chunk size. ### Method Signature ```csharp OpenUploadStream(string filename, GridFSUploadOptions options) OpenUploadStreamAsync(string filename, GridFSUploadOptions options) ``` ### Parameters #### Path Parameters - **filename** (string) - Required - The name of the file to upload. - **options** (GridFSUploadOptions) - Required - An instance of `GridFSUploadOptions` specifying configuration for the upload stream. ### Request Example (Synchronous) ```csharp var options = new GridFSUploadOptions { ChunkSizeBytes = 1048576 // 1 MB }; using (var uploader = bucket.OpenUploadStream("my_file", options)) { byte[] bytes = { 72, 101, 108, 108, 111, 87, 111, 114, 108, 100 }; // ASCII for "HelloWorld" uploader.Write(bytes, 0, bytes.Length); uploader.Close(); } ``` ### Request Example (Asynchronous) ```csharp var options = new GridFSUploadOptions { ChunkSizeBytes = 1048576 // 1 MB }; using (var uploader = await bucket.OpenUploadStreamAsync("my_file", options)) { byte[] bytes = { 72, 101, 108, 108, 111, 87, 111, 114, 108, 100 }; // ASCII for "HelloWorld" await uploader.WriteAsync(bytes, 0, bytes.Length); await uploader.CloseAsync(); } ``` ``` -------------------------------- ### Extended JSON Example - Canonical Source: https://www.mongodb.com/docs/drivers/csharp/current/document-formats/extended-json Represents BSON types without loss of information, prioritizing type preservation over human-readability. ```json { "_id": { "$oid": "573a1391f29313caabcd9637" }, "createdAt": { "$date": { "$numberLong": "1601499609" }}, "numViews": { "$numberLong": "36520312" } } ``` -------------------------------- ### Asynchronous Bulk Write with Custom Options Source: https://www.mongodb.com/docs/drivers/csharp/current/crud/bulk-write Use ClientBulkWriteOptions to configure an asynchronous bulk write operation. This example sets IsOrdered to false, WriteConcern to Unacknowledged, and VerboseResult to true. ```csharp var client = new MongoClient("mongodb://localhost:27017"); var deleteOneModel = new BulkWriteDeleteOneModel( "sample_restaurants.restaurants", Builders.Filter.Eq("restaurant_id", "5678") ); var clientBulkWriteOptions = new ClientBulkWriteOptions { IsOrdered = false, WriteConcern = WriteConcern.Unacknowledged, VerboseResult = true }; var result = await client.BulkWriteAsync(deleteOneModel, clientBulkWriteOptions); ``` -------------------------------- ### Run .NET Application Source: https://www.mongodb.com/docs/drivers/csharp/current/crud/restful-api-tutorial Command to execute the .NET application from the terminal. ```bash dotnet run ``` -------------------------------- ### NullIdChecker for Guid ID Validation Source: https://www.mongodb.com/docs/drivers/csharp/current/serialization/poco Apply `[BsonId(IdGenerator = typeof(NullIdChecker))]` to ensure the `Id` property is not null, throwing an exception if it is. ```csharp public class House { [BsonId(IdGenerator = typeof(NullIdChecker))] public Guid Id { get; set; } } ``` -------------------------------- ### Default Guid.Empty Behavior Source: https://www.mongodb.com/docs/drivers/csharp/current/serialization/guids When serializing Guid.Empty, the .NET/C# Driver treats it as an unset ID, which will be replaced by a new GUID upon insertion. ```csharp var doc = new MyDocument { Name = "Test" }; // Id will default to Guid.Empty collection.InsertOne(doc); // doc.Id will now contain a generated GUID, not Guid.Empty ``` -------------------------------- ### Create BulkWriteInsertOneModel Instances Source: https://www.mongodb.com/docs/drivers/csharp/current/crud/bulk-write Instantiate BulkWriteInsertOneModel for each document to be inserted. Specify the target collection namespace and the document content. ```csharp var restaurantToInsert = new BulkWriteInsertOneModel( "sample_restaurants.restaurants", new BsonDocument{ { "name", "Mongo's Deli" }, { "cuisine", "Sandwiches" }, { "borough", "Manhattan" }, { "restaurant_id", "1234" } } ); var movieToInsert = new BulkWriteInsertOneModel( "sample_mflix.movies", new BsonDocument{ { "title", "Silly Days" }, { "year", 2022 } } ); ``` -------------------------------- ### Unset Field in Many Documents (C#) Source: https://www.mongodb.com/docs/drivers/csharp/current/crud/update-many/fields Use `Update.Unset` to remove a field from all matching documents. This example removes the 'Cuisine' field. ```csharp var filter = Builders.Filter.Eq("name", "Shake Shack"); var update = Builders.Update .Unset(restaurant => restaurant.Cuisine); var result = _restaurantsCollection.UpdateMany(filter, update); ``` ```csharp var filter = Builders.Filter.Eq("name", "Shake Shack"); var update = Builders.Update .Unset(restaurant => restaurant.Cuisine); var result = await _restaurantsCollection.UpdateManyAsync(filter, update); ``` -------------------------------- ### Extended JSON Example - Shell Source: https://www.mongodb.com/docs/drivers/csharp/current/document-formats/extended-json Matches the syntax used in the MongoDB shell, often using JavaScript functions to represent types. ```json { "_id": ObjectId("573a1391f29313caabcd9637"), "createdAt": ISODate("2020-09-30T18:22:51.648Z"), "numViews": NumberLong("36520312") } ``` -------------------------------- ### Execute a Command Source: https://www.mongodb.com/docs/drivers/csharp/current/run-command Run a database command by creating a `BsonDocument` object and passing it to `RunCommand()` or `RunCommandAsync()`. You can specify the return type using a type parameter. ```APIDOC ## Execute a Command ### Description Run a database command by creating a `BsonDocument` object and passing it to `RunCommand()` or `RunCommandAsync()`. You can specify the return type using a type parameter. ### Method `RunCommand(BsonDocument command)` or `RunCommandAsync(BsonDocument command)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **command** (BsonDocument) - Required - A BsonDocument specifying the command to run. ### Request Example ```csharp var command = new BsonDocument("hello", 1); var result = database.RunCommand(command); // Or for asynchronous execution: // var result = await database.RunCommandAsync(command); ``` ### Response #### Success Response (200) - **``** (object) - Fields specific to the database command. - **`ok`** (double) - Indicates whether the command succeeded (`1.0`) or failed (`0.0`). - **`$clusterTime`** (object) - A document containing the signed cluster time (applies to replica sets or sharded clusters). - **`operationTime`** (object) - The logical time of the operation execution (applies to replica sets or sharded clusters). #### Response Example ```json { "topologyVersion": { "processId": { "id": "65f3a1b2c3d4e5f6a7b8c9d0" }, "counter": 1 }, "ok": 1.0, "$clusterTime": { "clusterTime": "660000000000000000000000", "signature": { "hash": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==", "keyId": "000000000000000000000000" } }, "operationTime": "660000000000000000000000" } ``` ``` -------------------------------- ### Configure Logging Settings Source: https://www.mongodb.com/docs/drivers/csharp/current/connect/connection-options Configure logging behavior by providing LoggingSettings. This allows setting the minimum log level, for example, to Debug. ```csharp var settings = new MongoClientSettings { LoggingSettings = new LoggingSettings( LoggerFactory.Create(l => l.SetMinimumLevel(LogLevel.Debug))) }; ```