Querying MongoDB using .NET Core

Querying MongoDB using .NET CoreQuerying MongoDB using .NET Core


The following article shows how to querying MongoDB using .NET Core.

MongoDB has recently released  the .NET Core support inside the C# driver (Net Core Support Driver). In fact, 2.3.0 version of C# Drivers has already been released to Nuget.

Querying MongoDB using .NET Core

The demo code is available on GitHub.

Setup the demo database

Firstly, you need to install MongoDB on your OS. Before continue, make sure that MongoDB is running correctly using:


Next, execute the following dump which creates the demo database:

mongo demoDB dump.js

Setup .NET Core project

I have previously discussed about .NET Core in the following articles:

Introducing ASP.NET 5 on Ubuntu

Future of ASP.NET is open source and cross platform

.NET Core and MVC: Customize view paths

There are different ways to use .NET Core on your OS, the following example uses the Yeoman aspnet-generator to scaffold a Web API template. It creates the following folder structure:
Samueles-MacBook-Pro:Blog.DotNetCoreMongoDb samueleresca$ tree
├── Controllers
│   └── ValuesController.cs
├── Dockerfile
├── Models
│   └── PostModel.cs
├── Program.cs
├── Properties
│   └── launchSettings.json
├── README.md
├── Startup.cs
├── appsettings.json
├── project.json
├── project.lock.json
├── web.config
└── wwwroot


project.json specifies the packages used by the project. Add the MongoDb drivers and launch the dotnet restore command inside the project folder to restore packages:

Defining model

You need to define a model which reflects the structure of your MongoDB collection, add the PostModel.cs file inside the Model folder:

Defining repository

PostsRepository is the core part of the project: it uses the MongoDB drivers to implement the CRUD operations on the Posts collection. Add the PostsRepository.cs file inside the Repository folder:

Defining controller

The PostsController handles the incoming HTTP requests and invokes the PostsRepository to return the query result:


You can run the webserver using the dotnet run command, and call Action methods  using a generic Web API client:

GET http://localhost:5000/api/posts
POST http://localhost:5000/api/posts?title="Title1"&content="Content1"&name="Test"

The code of this article is available on GitHub, at the following link.


Cheers 🙂