Overview
Hello Devs,
As we know there are many platforms available for Storing Databases for .NET Applications. In this blog, we are going to discuss MongoDB with .NET 5. We will learn why MongoDB is preferred, and why it’s best for storing data in MongoDB.
Introduction of MongoDB
MongoDB is a NoSQL database management program. We can say MongoDB is a tool that can retrieve and store data from the MongoDB database.
Why MongoDB?
MongoDB is representing information as a series of JSON.
MongoDB provides fast performance for storing data on databases and supports the feature insertMany() API for Bulk inserting data. We can say MongoDB provides fast performance for inserting and updating data on databases.
MongoDB with .NET 5
There are many reasons for using MongoDB with .NET, Let’s look at MongoDB with .NET 5.
.NET provides the NuGet package and supports all MongoDB Operations using MongoDB.Driver package.For Example
- Create Database
- Insert
- Update
- Delete
- Retrieve
- Bulk Insert, Update, Delete
- and many more Operations
CRUD Operations
So, We are going to create an API that performs CRUD operations on MongoDB.
In this Blog, we learn how to
- Creation of .NET Project
- Installation of NugGet Package
- Use of ConnectionString
- Creation of database
- Define a MongoDB collection and schema
- Perform MongoDB CRUD operations
Steps For creating .NET Project
- Go to File – New – Project.
- After creating the ASP.NET Core Web Application project, and select Next.
- Name the project generic. api, and select Create.
- Select the .NET Core target framework and ASP.NET Core 5.0. Click on the API template, and select to create a project.
Installation of NugGet Package
- Visit the NuGet package Gallery: MongoDB.Driver and install the stable release of MongoDB.Driver package.
- After installing the package go to Configure MongoDB.
Use ConnectionString
- So we can show The above image our connection to string, which will be our ConnectionString for our demo example.
- Set ConnectionString In the appsetting file.
- For that write ConnectionString as follows
“ConnectionStrings”: {“Default”: “mongodb://127.0.0.1:27017/mongo?directConnection=true&serverSelectionTimeo utMS=1000” }
Create database
Create one common file in the controller folder for defining connection and creating the database. For that, we need to create “CommonController.cs” in that we create a Database name as GenericDb and use ConnectionString that is set in Default.
public class CommonController:Controller { protected readonly IConfiguration configration; protected MongoClient empClient = null; protected IMongoDatabase Db = null; public CommonController(IConfiguration configurations) { configration = configurations; empClient = new MongoClient(configrations.GetConnectionString("Default")); Db = empClient.GetDatabase("GenericDb"); } }
Now we will use our CommonController on our every created API
Define a MongoDB collection and schema
- Schema Creation
we need to create an entity of schema in the model Folder, Here we give the schema name as Employee.using MongoDB.Bson; namespace generic.api.Models { [BsonIgnoreExtraElements] public class Employee { [BsonRepresentation(BsonType.ObjectId)] public string Id { get; set; } public int empNo { get; set; } public string eName { get; set; } public string Photo { get; set; } } }
- For Collection
Before creating an API, we need to create a Collection so that we create the following Constructor.public class EmployeeController : CommonController { private IMongoCollection _empTable = null; public EmployeeController(IConfiguration configurations) : base(configurations) { _empTable = database.GetCollection("employee"); } }
So our schema and Collection are ready. Our collection name is an employee. It’s stored and fetched data using the entity name Employee.
Perform MongoDB CRUD operations
Now time to create the first API, our first API will be inserted. Let’s see how to create an Insert API.
- Insert API
Using the OnsertOne() method of MongoDB we can insert one record at a time in the database like below Code example[HttpPost(ActionsConsts.Employee.InsertEmployee)] public IActionResult AddEmployee([FromBody] Employee empRequest) { _empTable .InsertOne(empRequest); return Ok("Successfully Inserted Record"); }
Input
Output
- Retrieve API
We are going to create a simple Get API for Retrieve Employee List using AsQueryable() method of MongoDB[HttpGet(ActionsConsts.Employee.RetrieveEmployee)] public IActionResult GetEmployee() { var EmployeeList = _empTable .AsQueryable(); return Json(EmployeeList); }
Output
- Update API
Here we are going to update eName By its empNo, Let’s see how it works.[HttpPost(ActionsConsts.Employee.UpdateEmployee)] public IActionResult UpdateEmployee([FromBody] Employee update) { var filter = Builders.Filter.Eq("eNumber",update.empNo); var updateEmployee = Builders.Update.Set("eName", update.eName); _empTable .UpdateOne(filter, updateEmployee); return OkResponse(“updated”); }
Input
Output
- Delete API
In Delete API we are going to Delete one record by employee Id because MongoDB provide By Default Primary key on the Id column so here requiredIdRequest is for our Id request[HttpPost(ActionsConsts.Employee.DeleteEmployee)] public IActionResult Delete([FromBody] RequiredIdRequest request) { _empTable .DeleteOne(x => x.Id == request.Id); return Ok("Deleted Successfully"); }
Input
Output
So, Here Output is Null because there is no record found in the employee collection.
Conclusion
So after going through MongoDB with .NET 5, we can say MongoDB stores data faster than any other database. Providing fast performance and less code of C#, we can perform operations using MongoDB’s default methods.