Querying 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.
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
│ └── ValuesController.cs
│ └── PostModel.cs
│ └── launchSettings.json
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:
You need to define a model which reflects the structure of your MongoDB collection, add the
PostModel.cs file inside the Model folder:
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
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:
The code of this article is available on GitHub, at the following link.