Working with MongoDB in .NET

Tuesday Jul 17th 2018 by Tapas Pal

Learn how to work with MongoDB from your .NET applications (C# code), and see the CRUD functions available from the .NET driver.


A NoSQL database is a document-oriented database system that stores data in a JSON-like format. MongoDB is classified as a Document NoSQL databases. It's one of the most popular and leading representatives of a Document databases system widely used in the industry. MongoDB gives users the ease of use and flexibility of JSON documents with the richness of a lightweight binary format. MongoDB represents JSON documents in a binary-encoded format called BSON. Its implementation is lightweight, fast, and highly traversable.

MongoDB provides drivers that allow you to connect with MongoDB from different programming languages. In this article, I'll demonstrate MongoDB installation, how to work with MongoDB from your .NET applications (C# code), and demonstrate the CRUD functions available from the .NET driver.

Why MongoDB?

MongoDB enables developers to store large volumes of data that have little or no structure. MongoDB is fast and can load a high volume of data and give you flexibility and availability in a Cloud-based environment. MongoDB helps to scale database architecture efficiently and inexpensively. With MongoDB's dynamic schemas, you can develop and release quickly.

MongoDB doesn't keep data in rows; it has documents. All the data for a given record is stored in a single document. From a programmer's point of view, MongoDB manipulates pure JSON files. Refer to the following example of a MongoDB document.

   "employeeid" : ObjectId("R8rGt541b1ad7d0c4rcfgt7549"),
   "employeename" : "Tapas Pal",
   "department" : "IT",
   "numberOfArticles" : 50,
   "Address" : [
      "street" : "Some Street",
      "city" : "Kolkata",
      "country" : "India"
   "companyname" : "XYZ",
   "skills" : [".NET", "JavaScript", "NoSQL", "Node.js", "HTML"]

Getting MongoDB

MongoDB is a free and open-source database. You can download it from the link given. MongoDB also provides a big list of drivers for different programming languages to communicate with the database. For use with .NET, we need to install the driver from NuGet package. The .NET driver includes MongoDB.Bson, MongoDB.Driver, and MongoDB.Driver.Core.

A .NET Project to Explain MongoDB Operations

Now, let's create a .NET console application to demonstrate CRUD operations on MongoDB. Make sure you run mongod.exe in the command prompt to keep the MongoDB server up and running while executing the console application.

Step 1

Open Visual Studio and create a C# console application project. Name it MongoDBConsoleApp.

The new console application
Figure 1: The new console application

Step 2

Next, we will need .NET drivers for MongoDB. To install the driver, right-click the solution and go to "Manage NuGet Packages." In the search bar, type "MongoDB" and install the package that appears. See Figures 2 and 3.

The "Manage NuGet Packages" link
Figure 2: The "Manage NuGet Packages" link

Package Manager output
Figure 3: Package Manager output

Step 3

Add the following namespaces in your Program.cs file. These namespaces are for connecting MongoDB and for CRUD operations.

using MongoDB.Driver;
using MongoDB.Bson;

Step 4

Next, we will write code to the CRUD operations. In this example, we will be using the BsonDocument class object to store the data in the MongoDB database.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Driver;
using MongoDB.Bson;
namespace MongoDBConsoleApp
   class Program
      static void Main(string[] args)
            MongoClient MongodbClient = new
            // Get Database and Collection
            IMongoDatabase Mongodb =
            var MongodbcollList =
            Console.WriteLine("The MongoDB list of collections
               are :");
            foreach (var item in MongodbcollList)
            var mydocument = Mongodb.GetCollection

            create(Mongodb, mydocument);
            update(Mongodb, mydocument);
            delete(Mongodb, mydocument);

            var myresultDoc = mydocument.Find(new
            foreach (var myitem in myresultDoc)
         catch (Exception ex)


      static void create(IMongoDatabase Mongodb, var mydocument)

         BsonElement employeename = new BsonElement("employeename",
            "Tapas Pal");
         BsonDocument empployee = new BsonDocument();
         empployee.Add(new BsonElement("employeenumber", 123));


      static void update(IMongoDatabase Mongodb, var mydocument)
         // UPDATE
         BsonElement updateemployee = new
            BsonElement("employeename", "Tapas1 Pal1");

         BsonDocument updateemployeedoc = new BsonDocument();
         updateemployeedoc.Add(new BsonElement("employeenumber",

         BsonDocument findemployeeDoc = new BsonDocument(new
            BsonElement("employeename", "Tapas Pal"));

         var updateDoc = mydocument.FindOneAndReplace
            (findemployeeDoc, updateemployeedoc);


      static void delete(IMongoDatabase Mongodb, var mydocument)
         // DELETE
         BsonDocument findAnotheremployee = new BsonDocument(new
            BsonElement("employeename", "Tapas1 Pal1"));


In the preceding code snippet's main method, I retrieved the current DB collection first. Next, I created a BsonDocument object where I stored employee data.

In the create method, I showed how to explicitly create a BsonElement object variable to store a key-value pair of employee objects and then added the object to the BsonDocument object.

In the update method, I directly passed the object as a parameter and found the employee name to update the details.

In the delete method, I deleted the employee created earlier.

Finally, I displayed the list.


In this article, we just saw the basic CRUD operations on MongoDB from .NET applications. I hope it helped you to get a basic understanding. Happy Coding!

Mobile Site | Full Site
Copyright 2018 © QuinStreet Inc. All Rights Reserved