How to write .Net Core Web API via Mongo DB on Windows Computer
Hello everyone,
I will try to explain ‘How to develop Dotnet Core Web Api via Mongo DB in Windows Computer’ in this article. Firstly, we should install MongoDB. You can use as follows link for download.
Let’s start to install.
You can cancel MongoDB Compass. I didn’t install it.
Now, we will add new value in environment variables. This is for command prompt screen. Not about Dotnet Core app. We will use mongoDB setup location in this step. My one is C:\Program Files\MongoDB\Server\4.2\bin If you want, you can skip this step.
We added two times. First one User variables for Your Username area and second one is system variables area. You should restart your computer after this step.
Let’s check MongoDB commands. We will just check some commands. First command is;
mongo
show databases
use databaseName
db.CreateCollection(“ExampleCollection”)
db.DropDatabase()
That’s enough for now. We can check all commands in another article. Now, Let’s start to write a web api.
I created and opened my project. Now, I will add mongoDB driver in my project. I’m using this command for add. My command is as follows.
dotnet add package MongoDB.Driver --version 2.9.2
You can check your package in .csproj file.
We will start from Model folder for development. Firstly, I will create Base model file. Because mongoDB is using Id field in collections. I will create this file for base.
Now, I will create an example model for my web api methods.
Now, I will create a base repository for my models. I will use this with my model repository.
Example model repository as follows.
We should add connection string property in appconfig.json file. We will use this in startup.cs file.
Startup.cs is as follows.
Example methods are as follows.
Now, I can see my database on command prompt.
You can download my example project in this link.
Best regards.