The key to integrating MongoDB with C# is to use official drivers and follow best practices. 1. Install the MongoDB.Driver package through NuGet; 2. Use MongoClient to connect to a local or Atlas database, and read the connection string from appsettings.json in the production environment; 3. Define a strongly typed C# class mapping document, use GetCollection
Integrating MongoDB with C# and the .NET ecosystem is straightforward and powerful, thanks to the official MongoDB C# driver and strong support across .NET platforms (including .NET 6, .NET Core, and .NET Framework). Whether you're building a web API with ASP.NET Core or a desktop application with Windows Forms, MongoDB fits in naturally.

Here's how to effectively integrate MongoDB into your C# projects.
1. Install the MongoDB C# Driver
The official MongoDB.Driver NuGet package provides everything you need to connect, query, and manage data in MongoDB from C#.

Install it via the Package Manager Console:
Install-Package MongoDB.Driver
Or using the .NET CLI:

dotnet add package MongoDB.Driver
This single package includes the core driver, BSON library, and support for LINQ queries.
2. Connect to MongoDB
Use MongoClient
to connect to your MongoDB instance. You can connect to a local instance or a cloud-hosted one like MongoDB Atlas.
var connectionString = "mongodb://localhost:27017"; // or your Atlas URI var client = new MongoClient(connectionString); // Access a specific database var database = client.GetDatabase("MyAppDb"); // Access a collection var collection = database.GetCollection<BsonDocument>("Users");
For production, store the connection string in appsettings.json
:
{ "ConnectionStrings": { "MongoDB": "mongodb srv://username:password@cluster0.xxxxx.mongodb.net/MyAppDb" } }
Then retrieve it using configuration services in ASP.NET Core:
var connectionString = Configuration.GetConnectionString("MongoDB");
3. Work with Strongly-Typed Documents
Instead of using BsonDocument
, define C# classes that map to your MongoDB documents.
public class User { [BsonId] public ObjectId Id { get; set; } [BsonElement("Name")] public string Name { get; set; } public string Email { get; set; } public List<string> Roles { get; set; } = new(); }
Now use a typed collection:
var collection = database.GetCollection<User>("Users");
Insert a document:
var user = new User { Name = "John Doe", Email = "john@example.com", Roles = new List<string> { "Admin", "User" } }; await collection.InsertOneAsync(user);
Query documents:
var filter = Builders<User>.Filter.Eq(u => u.Email, "john@example.com"); var result = await collection.Find(filter).FirstOrDefaultAsync();
Update a document:
var update = Builders<User>.Update.Set(u => u.Name, "Jane Doe"); await collection.UpdateOneAsync(filter, update);
Delete a document:
await collection.DeleteOneAsync(filter);
4. Use Dependency Injection in ASP.NET Core
Register MongoDB services in Program.cs
(or Startup.cs
in older versions):
builder.Services.AddSingleton<IMongoClient>(sp => { var settings = MongoClientSettings.FromConnectionString( builder.Configuration.GetConnectionString("MongoDB")); return new MongoClient(settings); }); builder.Services.AddScoped(sp => { var client = sp.GetRequiredService<IMongoClient>(); return client.GetDatabase("MyAppDb"); });
Then inject IMongoDatabase
into your controllers or services:
public class UsersController : ControllerBase { private readonly IMongoCollection<User> _users; public UsersController(IMongoDatabase database) { _users = database.GetCollection<User>("Users"); } [HttpGet] public async Task<IActionResult> Get() { var users = await _users.Find(_ => true).ToListAsync(); return Ok(users); } }
5. Handle Mapping and Conventions
The driver uses a BsonSerializer with conventions. You can customize them globally.
For example, automatically map camelCase
in JSON to PascalCase
in C#:
BsonSerializer.RegisterSerializationProvider(new ImmutableTypeClassMapSerializationProvider()); // Use camel case for field names var camelCaseConvention = new CamelCaseElementNameConvention(); ConventionRegistry.Register("CamelCase", new ConventionPack { camelCaseConvention }, _ => true);
Or ignore null values:
ConventionRegistry.Register("IgnoreNullValues", new ConventionPack { new IgnoreIfNullConvention(true) }, _ => true);
6. Use MongoDB with ORMs or Repositories
While MongoDB is schema-flexible, you can still apply clean architecture patterns.
Create a repository interface:
public interface IUserRepository { Task<User> GetByIdAsync(ObjectId id); Task<IEnumerable<User>> GetAllAsync(); Task CreateAsync(User user); Task UpdateAsync(User user); Task DeleteAsync(ObjectId id); }
Implement it using the MongoDB collection. This keeps your business logic decoupled.
7. Best Practices
Use indexes for frequently queried fields:
var indexKeys = Builders<User>.IndexKeys.Ascending(u => u.Email); await collection.Indexes.CreateOneAsync(new CreateIndexModel<User>(indexKeys));
Handle connection lifecycle properly—
MongoClient
is thread-safe and should be reused (singleton).Validate data before inserting—MongoDB doesn't enforce schema, so application-level validation is key.
Use async methods to avoid blocking calls, especially in web apps.
Enable logging and monitoring in production (eg, using MongoDB Atlas performance advisor).
Integrating MongoDB with C# feels natural once you get past the initial setup. With strong typing, LINQ support, and seamless DI integration, it's a solid choice for modern .NET applications. Just remember: flexibility doesn't replace structure—design your document models wisely.
Basically, it's not complex—but getting the setup right early saves headaches later.
The above is the detailed content of Integrating MongoDB with C# and the .NET Ecosystem. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Useproperindexesonquery,sort,andprojectionfields,favoringcompoundindexeswithequalitybeforerangefields,andavoidover-indexing;2.Optimizequeriesbyprojectingonlyneededfields,avoidingindex-blockingoperatorslike$whereandleading-wildcard$regex,andlimiting$i

Use Node.js, Socket.IO and MongoDB to build chat applications. First, build a technology stack and design a data model for users and messages. Use Mongoose to define schema and create indexes to improve query efficiency. Then, through Socket.IO, users join the room, send and receive messages in real time and load historical messages. After receiving the message, the server deposits it into MongoDB and pushes it to other members in the room. In order to support message history and expansion, use MongoDB query to sort messages by time to obtain messages, and load more content in combination with paging or infinite scrolling. It is recommended that MongoDBAtlas cloud service achieve automatic expansion and backup, and set TTL index to automatically clean up expired messages when necessary.

Designaroundaccesspatternsbyusingaflexibleschemawithembeddeddocumentsforperformance;includecommonfieldslikename,price,andsku,embedvariantandreviewdatawhenpractical,usearraysforspecifications,indexkeyfields,andseparatehigh-volumereviewstoensurescalabi

ShardingisessentialforscalingMongoDBwhendataexceedssingle-servercapacityorthroughputlimits,enablinghorizontalscalingbydistributingdataacrossmultipleshards.2.Ashardedclusterconsistsofshards(datastorage),mongosrouters(queryrouting),andconfigservers(met

EfficientstorageinMongoDBisachievedthroughoptimizedschemadesign,properindexing,andcompression.Usecompactschemaswithshortfieldnamesandappropriatedatatypes,embeddatawisely,andavoidunboundedarrays.LeverageWiredTiger’sSnappyorzlibcompressiontoreducedisku

MongoDB supports pattern matching using regular expressions, which is mainly implemented through the $regex operator or JavaScriptRegExp object; 2. Use db.users.find({name:{$regex:"john",$options:"i"}}) to find documents whose name field contains "john" and is case-insensitive; 3. You can also use JavaScript regular syntax such as db.users.find({email:/.*\.com$/i}) to match emails ending with ".com"

Monitorkeymetricslikeoperationexecutiontime,QPS,pagefaults,lockpercentage,andconnectioncounttodetectperformanceissuesearly.2.Usebuilt-intoolssuchasmongostat,mongotop,db.currentOp(),anddb.serverStatus()forreal-timeinsightsintodatabaseactivity.3.Levera

CreateaMongoDBAtlasaccountandverifyyouremail,thensetupaproject.2.Buildafree-tierclusteronapreferredcloudproviderandregion.3.ConfiguresecuritybyaddingadatabaseuserandallowingIPaccess.4.Connectusingtheconnectionstringinyourapplication.
