Hi,
I will try to explain “How to write .net core web api via MongoDB” in this post. Firstly, I should install MongoDB to my computer. Let’s get start. I used this link for download. Example screenshot is as follows.
After downloaded application, Let’s start to install it. The screenshots are as follows.
You can cancel MongoDB Compass. I didn’t install it.
After installation, I added new value in environment variables. This is for command prompt. I used 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.
I 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. I checked some commands. First command is;
mongo
show databases
use databaseName
db.CreateCollection(“ExampleCollection”)
db.DropDatabase()
That examples are enough for now. Maybe we can check all commands in another article. Now, let’s get start to web api.
I created and opened my project. After created project, I added mongoDB driver in my project. I used command for this as follows.
dotnet add package MongoDB.Driver –version 2.9.2
You can see this package in your .csproj file.
I started from model folder for development. Firstly, I created base model file. I added Id field because mongoDB is using Id field in collections. I created base model file for this. The screenshot is as follows.
After this file, I created an example model for my web api methods.
Now, I created a base repository for my models. I will use this with my model repository.
Example model repository is as follows.
I added connection string property in appconfig.json file. I 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.
Thanks.