MongoDB

How to Use MongoDB with C#: A Practical Guide

MongoDB is a document database for developing the applications in C# that need no SQL database. MongoDB is a database with scalability and manageability, and C# is a widespread language that is powerful with support for MongoDB through drivers. MongoDB is a perfect choice for C# applications that require flexibility without any involvement of SQL to store the data. MongoDB is easy to use, and we can install it on the system or we can use it on the cloud. For using MongoDB with C#, we need to install the related drivers.

To use MongoDB with C#, follow the steps that are discussed in the following. First, create a console program in Visual Studio. Here, we name the console application as “mongodbConn”. After creating the application, we need to install the drivers for MongoDB.

Prerequisite to Setup the MongoDB Drivers

Download the MongoDB from the official website of MongoDB. Next, open the Visual Studio or any IDE that you prefer for coding in C#. Then, install the driver for MongoDB C# through the NuGet Package Manager.

dotnet add package MongoDB.Driver --version 2.20.0

 
Execute the given command. The MongoDB driver will be added in the Visual Studio; the version may vary. Before installing, remember to check the version compatibility of the Visual Studio Code.

Connecting to MongoDB

To connect the console application to MongoDB, we need the “atlas connection” string that usually looks like this:

mongodb://localhost:27017

 
There are a few changes that we need to make in the previous string. Remember to change the “localhost” with the MongoDB server and change the port 27017 with the MongoDB port. Now, to make the driver work, we need to add the following string in the C# console application:

using MongoDB.Driver;

 
The previous string tells the compiler that we are using the MongoDB driver.

var connString = "mongodb://localhost:27017";
var M_client = new MongoClient(connString);

 
The previous string creates an instance of the MongoClient to connect to MongoDB.

Selecting the Database

To select the database, include the following piece of code in the console application code:

var myDb = M_client.GetDatabase("myProject");

 
In this step, we select the database in which we want to store the data and store that in a variable. Keep in mind that “myProject” is the name of the database here in our case.

There are numerous databases in Mongoose, and each database is capable of holding numerous collections. So, to store the data in the right collection, we need to write the correct database and collection name. The collections work the same as the tables in SQL.

Selecting the Collection

To select the collection, include the following portion of code in the console application code:

var myCollection = myDb.GetCollection<BsonDocument>("myProjectCollection");

 
In this step, we select the database in which we want to store the data and store that in a variable. Here, a few adjustments are required. Remember that “myProjectCollection” is the name of the database collection.

MongoDB CRUD (Create, Read, Update, and Delete) Queries

We carry out the CRUD procedures on all databases. Either we need to create a record, read it, manipulate it, or else delete it. Mongoose stores the data in binary JSON form which is why we need to work with BSON documents.

Example 1: Insert the Data in MongoDB through C#

This example inserts the data of a person in MongoDB while coding in C#.

using System;
using MongoDB.Driver;
namespace mongodbConn
{
    class Program1
    {
        static void Main(string[] args)
        {
var connString = "mongodb://localhost:27017";
var M_client = new MongoClient(connString);
var myDb = M_client.GetDatabase("myProject");
var myCollection = myDb.GetCollection<BsonDocument>("myProjectCollection");
var doc = new BsonDocument
{
    { "name", "ht" },
    { "age", "39" },
   { "cnic", "1234567896779" },
    { "email", "ht@gmail.com" }
};
myCollection.InsertOne(doc);    
   }
    }
}

 
In this example code, import the packages first. The first package uses a system that is compulsory to import. Then, import the MongoDB driver. In the main function, create the database connection by defining the connection string, database name, and collection name.

To insert the collection, we use the BSON format. We can insert the data using the query or BSON format. Since Mongoose stores the data in binary JSON format, when we insert the data in MongoDB through C#, we can code in BSON format. We can also use the query instead of BSON format. Next, create a BSON document store name, age, cnic, and email.

After writing the data, use the “insertOne” method to insert it in the “myCollection”. This stores the data in the MongoDB, executes the code, and opens the MongoDB to verify whether the data is stored successfully or not.

The output shows that the record is inserted in the database which includes the name, age, cnic, and email. The ID is automatic, and each record has its own ID:


 

Example 2: Update the Age in MongoDB through C#

This example updates the records that are already stored in MongoDB.

using System;
using MongoDB.Driver;
namespace mongodbConn
{
    class Program1
    {
        static void Main(string[] args)
        {
var connString = "mongodb://localhost:27017";
var M_client = new MongoClient(connString);
var myDb = M_client.GetDatabase("myProject");
var myCollection = myDb.GetCollection<BsonDocument>("myProjectCollection");

var filt = Builders<BsonDocument>.Filter.Eq("name", "ht");
var update = Builders<BsonDocument>.Update.Set("age", 30);
myCollection.UpdateOne(filt, update);
   }
    }
}

 
In this example code, import the packages first. Then, establish the connection. Then, establish the connection by connecting to MongoDB, then to the database, and then to the collection of the database. Now, filter the record or a field to delete the items. When we filter, it means that we will look for this specific data in the determined database. After filtering the data, we can either update it or delete it.

In this example, we update the data that we just stored in MongoDB in the first example. This example filters the record with the name as “ht” and then updates the age of “ht” from 39 to 30. The Update.Set sets the person’s age by replacing the existing one with the new age that we added in the Update.Set. In the end, update one collection by passing two variables, filter the record, and update to update the specified field of a record.

This output shows that the record is updated successfully. The age is updated from 39 to 30:

Example 3: Delete a Record in MongoDB through C#

This example deletes the data that is already stored in the database.

using System;
using MongoDB.Driver;
namespace mongodbConn
{
    class Program1
    {
        static void Main(string[] args)
        {
var connString = "mongodb://localhost:27017";
var M_client = new MongoClient(connString);
var myDb = M_client.GetDatabase("myProject");
var myCollection = myDb.GetCollection<BsonDocument>("myProjectCollection");
var filt = Builders<BsonDocument>.Filter.Eq("name", "ht");
myCollection.DeleteOne (filt);
   }
    }
}

 
In this example code, import the packages first. Then, establish the connection. Then filter the record that we want to delete. In “myProjectCollection”, there is only one record; when we delete that record, the collection will become empty. To delete, we need to perform two steps. First, filter the record, then use the DeleteOne to delete the filtered record from MongoDB.

The output shows that there is no data in the database after deletion; the “myProjectCollection” becomes empty. After executing the deletion, there is no data because there was only a single data in the database:

Conclusion

Databases play a vital role when dealing with applications that need to store their data. MongoDB is the best choice for storing the data in the document form. Integrating C# and MongoDB makes things easier for programmers. We can easily perform the CRUD operation on MongoDB in C# by following the elaborated steps.

About the author

Saeed Raza

Hello geeks! I am here to guide you about your tech-related issues. My expertise revolves around Linux, Databases & Programming. Additionally, I am practicing law in Pakistan. Cheers to all of you.