Querying MongoDB using .NET Core
The following article shows how to 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:
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.
Subscribe to our newsletter
Get the latest posts delivered right to your inbox.