How to connect to MongoDB from C#?

21 februari 2022 om 10:00 by ParTech Media - Post a comment

In our previous blog, we had introduced you to the Mongo database along with its purpose. In this post, we will go one step ahead and try to understand how it can be clubbed with a C# application.

Table of contents

  1. Software required
  2. Connecting to MongoDB from C#
  3. Conclusion

Software required

Before we jump into the main content of this blog, here are some tools you will need -

  1. Mongo server - Local instance (https://docs.mongodb.com/guides/server/install/),
  2. MongoDB Compass (Tool to visualize the Mongo collection and documents)
  3. Visual Studio IDE

Connecting to MongoDB from C#

We are going to create a C# based web API that will be performing Create, Read, Update and Delete operations in the Mongo database. But before we implement the coding component in C# to achieve connectivity, we will set up the Local Mongo collection.

Once the Mongo server is installed locally, follow the instructions provided in the link above to get the server up and running locally. There are different ways to create databases and collections in Mongo. We are going to use the MongoDB Compass to create them.

Open the MongoDB Compass and provide the connection string of the local server and connect to it.

Typically it would be - mongodb://127.0.0.1:27017

Once connected, on the left pane, you will notice three pre-created databases - admin, config, and local. On the same screen, there will be an option to create a new database as well.

For our purpose, we are not going to create a new database. Instead, we are going to make use of the admin database and create a new collection in it. To create a new collection, we are going to click on the plus icon next to the admin database on the left pane. It opens a popup with a collection creation option as below. Provide a name and create the collection.

Once the collection is created, add sample data by clicking on the Insert Document option in the drop-down menu. In the popup, provide JSON of the below kind (data as required) to create a document in the created collection.

{
  "_id": {
​    "$oid": "6210ad9aa8fb2b27c1ac20c0"
  },

  "employeeId": 124,
  "name": "Smith",
  "company": "PARTECH",
  "salary": 11000
}

Here, we have named the collection PARTECH and we are trying to store Employee data in it. And the document contains properties like EmployeeId, Name, Company, and Salary.

We are going to consume this collection in our code and do a CRUD operation with it from the C# code.

First, let's create an ASP.Net Core-based web application and provide a valid name for the solution. .Net 5 frameworks have been chosen to develop the application.

Once the project is created, the folder structure looks as below.

Now let's add the NuGet package.

We are going to add a few new classes in this project to handle the data from the database and to make connections to the database. First, we will create a Models folder and create a PARTECH class inside it with the below properties.

public class PARTECH
  {
​    [BsonId]
​    public ObjectId _id { get; set; }
​    public int EmployeeId { get; set; }
​    public string Name { get; set; }
​    public string Company { get; set; }
​    public long Salary { get; set; }
  }

Next, we will create a DataLayer folder and create two files inside it, one being the interface and another being the class file that inherits the interface. Using these files, we are going to establish a connection with MongoDB.

Similar to any other database connection, the connection string has to be stored in the app config, so that it can be modified as required. The connection string is going to be added in the appsettings.json file and the content to be added will be

"ConnectionStrings": {
  "MongoDB": "mongodb://127.0.0.1:27017"
 }

Now, we have the database connection string, a model for reading the data, and empty classes (which are going to be written with code that communicates with the database).

Let's open the file, IMongoHelper.cs, and add the below contents

using MongoDB.Driver;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace PARTECH_MongoDB.DataLayer
{
  public interface IMongoHelper
  {
​    Task<List<T>> GetAllDocuments<T>(string dbName, string collectionName);
​    Task<List<T>> GetFilteredDocuments<T>(string dbName, string collectionName, FilterDefinition<T> filter);
​    Task UpdateDocument<T>(string dbName, string collectionName, FilterDefinition<T> filter, UpdateDefinition<T> document);
​    Task CreateDocument<T>(string dbName, string collectionName, T document);
​    Task DeleteDocument<T>(string dbName, string collectionName, FilterDefinition<T> filter);
  }
}

Now, let's open the MongoHelper.cs file and add the below contents

using Microsoft.Extensions.Configuration;
using MongoDB.Driver;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace PARTECH_MongoDB.DataLayer
{
  public class MongoHelper : IMongoHelper
  {
​    private readonly IConfiguration _configuration;
​    public MongoHelper(IConfiguration config)
​    {
​      _configuration = config;
​    }

​    public IMongoDatabase GetMongoDbInstance(string dbName)
​    {
​      var connString = _configuration.GetConnectionString("MongoDB");
​      var client = new MongoClient(connString);
​      var db = client.GetDatabase(dbName);
​      return db;
​    }

​    private IMongoCollection<T> GetCollection<T>(string dbName, string collectionName)
​    {
​      return GetMongoDbInstance(dbName).GetCollection<T>(collectionName);
​    }

​    public async Task<List<T>> GetAllDocuments<T>(string dbName, string collectionName)
​    {
​      var collection = GetCollection<T>(dbName, collectionName);
​      return await collection.Find(x => true).ToListAsync();
​    }

​    public async Task<List<T>> GetFilteredDocuments<T>(string dbName, string collectionName, FilterDefinition<T> filter)
​    {
​      return await GetCollection<T>(dbName, collectionName).Find(filter).ToListAsync();
​    }

​    public async Task UpdateDocument<T>(string dbName, string collectionName, FilterDefinition<T> filter, UpdateDefinition<T> document)

​    {
​      await GetCollection<T>(dbName, collectionName).UpdateOneAsync(filter, document);
​    }

​    public async Task CreateDocument<T>(string dbName, string collectionName, T document)
​    {
​      await GetCollection<T>(dbName, collectionName).InsertOneAsync(document);
​    }

​    public async Task DeleteDocument<T>(string dbName, string collectionName, FilterDefinition<T> filter)

​    {
​      await GetCollection<T>(dbName, collectionName).DeleteOneAsync(filter);
​    }
  }
} 

The next step is to inject the IMongoHelper in Startup.cs file.

Add the below line in the ConfigureServices method

services.AddSingleton<IMongoHelper, MongoHelper>();

Now let's create a new controller and name it as MongoController.cs and add the below contents inside it.

 public class MongoController : ControllerBase

  {

​    private readonly ILogger<MongoController> _logger;
​    private readonly IMongoHelper _mongoHelper;
​    public MongoController(ILogger<MongoController> logger, IMongoHelper mongo)
​    {
​      _logger = logger;
​      _mongoHelper = mongo;
​    }

​    [HttpGet]
​    public async Task<IEnumerable<PARTECH>> Get()
​    {
​      return await _mongoHelper.GetAllDocuments<PARTECH>("admin", "PARTECH");
​    }

​    [HttpGet("GetByName")]
​    public async Task<IEnumerable<PARTECH>> GetByName(string name)
​    {
​      var filter = Builders<PARTECH>.Filter.Eq("Name", name);
​      return await _mongoHelper.GetFilteredDocuments<PARTECH>("admin", "PARTECH", filter);
​    }

​    [HttpPatch("UpdateNameAndSalary")]
​    public async Task UpdateDetails(PARTECH partechData)
​    {
​      var filter = Builders<PARTECH>.Filter.Eq("EmployeeId", partechData.EmployeeId);
​      var update = Builders<PARTECH>.Update.Set(x => x.Name, partechData.Name).Set(x => x.Salary, partechData.Salary);

​      await _mongoHelper.UpdateDocument<PARTECH>("admin", "PARTECH", filter, update);
​    }

​    [HttpPost]
​    public async Task CreateDetails(PARTECH partechData)
​    {
​      await _mongoHelper.CreateDocument<PARTECH>("admin", "PARTECH", partechData);
​    }

​    [HttpDelete]
​    public async Task DeleteDetails(int id)
​    {
​      var filter = Builders<PARTECH>.Filter.Eq("EmployeeId", id);
​      await _mongoHelper.DeleteDocument<PARTECH>("admin", "PARTECH", filter);
​    }
  }

Now, let's build and run the solution; a swagger should open up.

Let's try the Get method without any input parameters. The result should look like below.

Now, let's add up new employee details using the post.

Next, we will try to search this person by name in the HttpGet with the input parameter.

Next, we will delete the details of the employee id - 456.

Lastly, we will try an ‘update’ on employee id - 123.

Final Thoughts

You have successfully connected MongoDB with C# and performed CRUD operations in it. This post should help you set up and work with MongoDB and C# based projects in the future.

Nieuwste