Getting Started MongoDB in .NET Core with Examples
In this article, we will see how to Getting Started MongoDB in .NET Core Example using C# Driver.
We shall be using the MongoDB database as the NoSQL database instance and will create an API application using in .NET Core 3.1 or .NET 6.0 application.
We shall be following the below steps overall for today’s article,
We shall create a MongoDB context object which will resemble SQL pseudo-EF Core generated DBContext scaffolding. (ORM framework for relational DB.)
Here we shall create a Context class that will help us to create abstraction around the Mongo Database object.
Getting Started
Create an ASP.NET Core API
You can use ASP.NET Core 3.1 or .NET 5/6 project as required.
Add MongoDB Driver Nuget package
Please add the MongoDB driver NuGet package using the Nuget Package manager.
Or
Using NuGet Package Manager
PM> Install-Package MongoDB.Driver -Version 2.9.3
Note: Please use the latest available version
MongoDB Configuration
Below is the MongoDB connection configuration defined in the sample appsettings.json.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"MongoSettings": {
"Connection": "//your connection string ",
"DatabaseName": "Book"
}
}
Let’s create a Mongosettings class that will represent the above configuration using the typesafe configuration technique we learned in our last article.
Below is Mongosettings class defined,
public class Mongosettings
{
public string Connection { get; set; }
public string DatabaseName { get; set; }
}
Please see below the code which we shall be achieving ultimately.
This will give the idea that we will need below new types like defining IMongoBookDBContext, MongoBookDBContext, and Book class which will help us connect the database and perform Create, Read, Update and delete operation using supported extension methods.
Use Repository pattern to abstract the code communicating to databse. Please refer below link for Repository implementation using MongoDB,
1. Define DBContext Interface
DBContext Interfaces will be defined as below,
public interface IMongoBookDBContext
{
IMongoCollection<T> GetCollection<T>(string name);
}
2.Define DBContext class
DBContext class will be defined as below,
public class MongoBookDBContext : IMongoBookDBContext
{
private IMongoDatabase _db { get; set; }
private MongoClient _mongoClient { get; set; }
public IClientSessionHandle Session { get; set; }
public MongoBookDBContext(IOptions<Mongosettings> configuration)
{
_mongoClient = new MongoClient(configuration.Value.Connection);
_db =_mongoClient.GetDatabase(configuration.Value.DatabaseName);
}
public IMongoCollection<T> GetCollection<T>(string name)
{
return _db.GetCollection<T>(name);
}
}
So DBContext class will help to establish an actual connection, providing the database collection as required. If needed you can expose MongoClient objects to users by making them public.
3. Create DB Models entity i.e Book
Based on the schema this is how the model class has been defined below,
Schema Modelling for MongoDB
public class Book
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
public string Author { get; set; }
}
So finally we are all set with the Models and types required for us to connect and perform our CRUD operation.
MongoDB in .NET Core Example – Configure DI in Startup.cs
Please update the ConfigureService methods for injecting the MongoBookDBContext into the service container.
Note – Above we have used Singleton instance of MongoContext object and hence Mongo Driver instance which is recommended approach.
Similarly, key-value pairs in the form of primitives i.e string can be injected using IOption or IConfiguration pattern
The final implementation for the Controller methods is as below. Here the example is given for GET method only. You can create other methods similarly as required.
[ApiController]
public class BookController : ControllerBase
{
private readonly IMongoBookDBContext _context;
protected IMongoCollection<Book> _dbCollection;
public BookController(IMongoBookDBContext context)
{
_context = context;
_dbCollection= _context.GetCollection<Book>(typeof(Book).Name);
}
[HttpGet]
[Route("books")]
public async Task<ActionResult<IEnumerable<Book>>> Get()
{
var all = await _dbCollection.FindAsync(Builders<Book>.Filter.Empty);
return Ok(all.ToList());
}
We are using the Findsync method which is an extension method.
MongoDB in .NET Core Example – GET Method
Let’s execute the GET API and verify the results,
That’s all this was very much basics on connecting the MongoDB database using MongoDB Driver C# code.
References:
Do you see any further improvement to this codebase ??
Please do use the Repository pattern around MongoDB as discussed in the below implementation,
Summary
Today in this article we learned how to connect to the MongoDB database using MongoDB C# Driver. We looked at simple and easy-to-understand ASP.NET Core implementation performing basic CRUD operations. We also found that application with a complex business/domain model gets a huge advantage if data is accessed using the Repository which we quickly sensed while going through the article.
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.
You should add your MongoBookDBContext class as Singleton according netcore mongodb driver docs. Using Scoped DI, when your application receives too many requests, the number of connections will increase and impact the performance of the Mongo server.
Thank you Renato for your inputs.Appreciate it. I will make sure I count that “best practices” and will make a note on this article. Have a good day!
In the IMongoBookDBContext why would you specify the type? Why would it not be:
IMongoCollection GetCollection(string name);
Hello Noah- Thanks for the query. That’s a good point. I did corrected the interface definitions and made it more generic using T.
Thanks for the article.
It was very helpfull, and got the job done, after a long search.
You might need to add
services.AddScoped();
to the startup file.
Thanks, Lanre, glad article helped you.
Yes, it generally needs to scoped or singleton but not transient as a good practice. I shall update that soon. good catch!