:::: MENU ::::

Using MongoDB with ASP.NET Core – Part II (Implementation)

In first post, i talked about MongoDB briefly and showed how to set up local environment to work with MongoDB.

In this second post, I will show you how to actually use MongoDB as a data storage with ASP.NET Core application with simple CRUD operation. As I mentioned earlier I am using ASP.NET Core Web API for this article.

First let’s create simple Asp.Net Core Web API project and add MongoDB package from nuget in project.json.

Here, I am storing employee details on MongoDB storage. So I am creating Employee model to represent employee.

Now I am adding basic CRUD operations and I will wrap those functions with EmployeeRepository class. (You can extract this method on Interface too)

On the constructor I initiate connection with Mongodb Server. Read how to set up mongo server and client in my previous post. Connection is done now lets perform CRUD operation.

Note: For demo i am initiating connection in repository class but in real application my recommendation is create separate handler for connection purpose as well as for referencing Mongo collection (make it generic).

CREATE

Basic idea here is getting reference of collection where we want to add document and adding object on that with one of the available insert option.

Note: There are lots of  different methods with different signatures for different scenario but for same purpose in CRUD operation. Here i am only showing how to get started. So choose best approach for your case.

READ

-All

First it takes refrence of our targeted collection and perform find operation with empty FilterDefinition. An empty filter matches everything.

-With Filter

First i am preparing filtering condition. In my case, filter is done base on EmployeeId then passing filter to find the matched object.

Note: You need to change separation function (FirstOrDefault()) as per your need.

UPDATE

Same as above, preparing two definition. One for object filter and another for update then passing both filter on update function. Update function returns UpdateResult type object so you can process other task base on that result.

DELETE

Again, preparing filter definition to select object that we want to delete and pass that definition to actually delete that selected object.

Now test all function with Postman (or your choice of tool) to verify weather its functioning well or not.

Quick Tip: Use db.<CollectionName>.find() for getting all data in console like PowerShell. It helps to check changes faster than hitting another get request in postman. Steps are easy, start console and connect mongo client with your database by command “mongo <dbname>” and get all data with command “db.<CollectionName>.find()”.

That’s all. This is how you can get started with MongoDB in ASP.NET Core application. Source code is available in GitHub.

Happy Coding !!!


  • bpun

    Nice article…