MongoDB.Driver for C# (.NET): Complete Guide with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

MongoDB.Driver for C# (.NET): Complete Guide

\n\n

1. What It Is and Why It's Needed

\n\n

MongoDB.Driver is the official, high-performance, asynchronous driver for .NET platform applications (C#, F#, VB.NET) to interact with the MongoDB database. It provides a full set of tools for performing all CRUD operations (Create, Read, Update, Delete), managing indexes, data aggregation, working with transactions, and processing real-time changes (Change Streams). The driver is developed and maintained by MongoDB Inc., which guarantees its full compatibility with the latest versions of MongoDB and implementation of all modern DBMS capabilities.

\n\n

Why is this library needed? If you are developing a .NET application (ASP.NET Core web service, WPF desktop application, console utility, or microservice) and want to use MongoDB as your primary or secondary data storage, you need a driver to establish a connection and exchange data. MongoDB.Driver abstracts the complexity of the MongoDB Wire Protocol, providing the developer with a convenient, strongly typed API. You work with C# objects, and the driver automatically serializes them to BSON (MongoDB's binary format) and back. This allows you to write concise, safe, and performant code without delving into low-level interaction details.

\n\n

The library supports two main paradigms: synchronous and asynchronous (recommended). Asynchronous methods (with the Async suffix) prevent blocking execution threads, which is critical for scalable server applications. The driver also includes a LINQ provider that translates LINQ queries into MongoDB Aggregation Pipeline syntax, making the code even more declarative and familiar for .NET developers.

\n\n

2. Installation

\n\n

Installation is done via the NuGet package manager. Run one of the following commands in the Package Manager Console or in the .NET CLI terminal.

\n\n

Via .NET CLI (recommended):

\n
dotnet add package MongoDB.Driver
\n\n

Via Package Manager Console (Visual Studio):

\n
Install-Package MongoDB.Driver
\n\n

For projects using Entity Framework Core (optional):

\n

There is a separate provider MongoDB.EntityFrameworkCore, but for most tasks the main driver is sufficient.

\n\n

After installation, a reference will be added to the project file (.csproj):

\n
<PackageReference Include="MongoDB.Driver" Version="2.25.0" />
\n\n

3. Quick Start — Minimal Working Example

\n\n

The following code connects to a local MongoDB instance, gets the "testdb" database, the "users" collection, inserts one document, and prints its ID to the console.

\n\n
using MongoDB.Bson;\nusing MongoDB.Driver;\n\n// 1. Create a client (connection to the server)\nvar client = new MongoClient("mongodb://localhost:27017");\n\n// 2. Get the database (created automatically if it doesn't exist)\nvar database = client.GetDatabase("testdb");\n\n// 3. Get the collection (created automatically on first insert)\nvar collection = database.GetCollection<BsonDocument>("users");\n\n// 4. Create a document\nvar document = new BsonDocument\n{\n    { "name", "Alice" },\n    { "age", 30 },\n    { "city", "New York" }\n};\n\n// 5. Insert the document (asynchronously)\nawait collection.InsertOneAsync(document);\n\n// 6. Print the generated ID\nConsole.WriteLine($"Document inserted with ID: {document["_id"]}");\n\n// 7. Read all documents from the collection\nvar allUsers = await collection.Find(new BsonDocument()).ToListAsync();\nforeach (var user in allUsers)\n{\n    Console.WriteLine(user.ToJson());\n}
                
    
    

Recommendations