Using MongoDB in a .NET Core application is straightforward, thanks to the official MongoDB .NET driver. Here’s a comprehensive guide on setting up MongoDB in a .NET Core application, connecting to the database, and performing CRUD operations.
1. Setting Up MongoDB in .NET Core
Step 1: Install the MongoDB Driver
Add the MongoDB.Driver package to your project using NuGet Package Manager or by running the following command in the Package Manager Console:
Install-Package MongoDB.Driver
Step 2: Configure MongoDB in appsettings.json
Define your MongoDB connection string and database name in appsettings.json
. For example:
{
"MongoDBSettings": {
"ConnectionString": "mongodb://localhost:27017",
"DatabaseName": "MyDatabase"
}
}
Step 3: Create a Configuration Class for MongoDB Settings
Create a class to map the settings in appsettings.json
:
public class MongoDBSettings
{
public string ConnectionString { get; set; }
public string DatabaseName { get; set; }
}
2. Register MongoDB in the Dependency Injection (DI) Container
In Startup.cs
or Program.cs
(depending on your .NET Core version), register the MongoDB settings and client in the DI container.
public void ConfigureServices(IServiceCollection services)
{
// Bind MongoDB settings from appsettings.json
services.Configure<MongoDBSettings>(Configuration.GetSection("MongoDBSettings"));
// Register MongoClient
services.AddSingleton<IMongoClient>(sp =>
{
var settings = sp.GetRequiredService<IOptions<MongoDBSettings>>().Value;
return new MongoClient(settings.ConnectionString);
});
// Register your MongoDB service (explained in next section)
services.AddScoped<IMyEntityService, MyEntityService>();
}
3. Create a MongoDB Service
This service will handle database operations. Let’s create a sample service called MyEntityService
for managing a collection called MyEntities
.
Step 1: Define the Entity Class
Create a model representing the MongoDB document. MongoDB requires an _id
field of type ObjectId
(or string
if using GUIDs for IDs).
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
public class MyEntity
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
Step 2: Define the Service Interface
Create an interface for your service with basic CRUD operations.
public interface IMyEntityService
{
Task<IEnumerable<MyEntity>> GetAllAsync();
Task<MyEntity> GetByIdAsync(string id);
Task CreateAsync(MyEntity entity);
Task UpdateAsync(string id, MyEntity entity);
Task DeleteAsync(string id);
}
Step 3: Implement the Service
Implement IMyEntityService
using MongoDB’s driver methods.
using MongoDB.Driver;
using Microsoft.Extensions.Options;
public class MyEntityService : IMyEntityService
{
private readonly IMongoCollection<MyEntity> _myEntities;
public MyEntityService(IMongoClient client, IOptions<MongoDBSettings> options)
{
var database = client.GetDatabase(options.Value.DatabaseName);
_myEntities = database.GetCollection<MyEntity>("MyEntities");
}
public async Task<IEnumerable<MyEntity>> GetAllAsync()
{
return await _myEntities.Find(_ => true).ToListAsync();
}
public async Task<MyEntity> GetByIdAsync(string id)
{
return await _myEntities.Find(e => e.Id == id).FirstOrDefaultAsync();
}
public async Task CreateAsync(MyEntity entity)
{
await _myEntities.InsertOneAsync(entity);
}
public async Task UpdateAsync(string id, MyEntity entity)
{
await _myEntities.ReplaceOneAsync(e => e.Id == id, entity);
}
public async Task DeleteAsync(string id)
{
await _myEntities.DeleteOneAsync(e => e.Id == id);
}
}
4. Using the MongoDB Service in a Controller
Create a controller to expose these CRUD operations via API endpoints.
[ApiController]
[Route("api/[controller]")]
public class MyEntitiesController : ControllerBase
{
private readonly IMyEntityService _myEntityService;
public MyEntitiesController(IMyEntityService myEntityService)
{
_myEntityService = myEntityService;
}
[HttpGet]
public async Task<IActionResult> GetAll()
{
var entities = await _myEntityService.GetAllAsync();
return Ok(entities);
}
[HttpGet("{id:length(24)}", Name = "GetById")]
public async Task<IActionResult> GetById(string id)
{
var entity = await _myEntityService.GetByIdAsync(id);
if (entity == null) return NotFound();
return Ok(entity);
}
[HttpPost]
public async Task<IActionResult> Create(MyEntity entity)
{
await _myEntityService.CreateAsync(entity);
return CreatedAtRoute("GetById", new { id = entity.Id }, entity);
}
[HttpPut("{id:length(24)}")]
public async Task<IActionResult> Update(string id, MyEntity entity)
{
var existingEntity = await _myEntityService.GetByIdAsync(id);
if (existingEntity == null) return NotFound();
await _myEntityService.UpdateAsync(id, entity);
return NoContent();
}
[HttpDelete("{id:length(24)}")]
public async Task<IActionResult> Delete(string id)
{
var entity = await _myEntityService.GetByIdAsync(id);
if (entity == null) return NotFound();
await _myEntityService.DeleteAsync(id);
return NoContent();
}
}
5. Running the Application
- Configure MongoDB: Ensure MongoDB is running locally or use a hosted MongoDB service.
- Run the Application: Start your .NET Core application, and you can now interact with the MongoDB collection using the API endpoints in
MyEntitiesController
.
Additional Considerations
- Error Handling: Add error handling to manage exceptions, especially for database connectivity or invalid inputs.
- Connection Pooling: The MongoDB .NET driver handles connection pooling automatically. Ensure proper usage by reusing a single
IMongoClient
instance. - Indexes: Create indexes in MongoDB for fields that will be queried frequently to improve performance.
This setup provides a structured approach to integrate MongoDB into a .NET Core application with dependency injection, making it suitable for scalable and maintainable projects.