Getting Started With MongoDB - MongoDB With C#

In my previous article, you got a little knowledge about the basics of MongoDB. This article will focus on performing CRUD operations from a C# console application. The working mechanism will be the same for web applications and desktop applications. Open up mongod.exe in the command prompt to keep the MongoDB server running while executing our C# application.
 
To get started, open Visual Studio and create a C# console application project.

 

Now, we will need .NET drivers for MongoDB to interact with the database server. So, right-click on the solution and go to "Manage NuGet Packages". In search bar, type "MongoDB" and install the first package that appears.

 
 
 
That's it. You are done with the drivers and now you can dive into the code. First, we need the connection string to connect to the database. You will get the connection string when you fire up the mongo.exe.

 
Then we need a MongoDB client to interact with the server. 
  1. MongoClient dbClient = new MongoClient("mongodb://127.0.0.1:27017");  
Click on "MongoClient", press "Ctrl + ." and press Enter to add the namespace "MongoDB.Drivers". Now, let's try to execute some database commands.
  1. //Database List  
  2. var dbList = dbClient.ListDatabases().ToList();
  3.   
  4. Console.WriteLine("The list of databases are :");  
  5. foreach (var item in dbList)  
  6. {  
  7.    Console.WriteLine(item);  
  8. }  
This code shows a list of databases present on the Server. Pretty easy, right?
 
Let's take a look at another one.
  1. //Get Database and Collection  
  2. IMongoDatabase db = dbClient.GetDatabase("test");  
  3. var collList = db.ListCollections().ToList();  
  4. Console.WriteLine("The list of collections are :");  
  5. foreach (var item in collList)  
  6. {  
  7.    Console.WriteLine(item);  
  8. }  
Now, it is time for some CRUD operations. As I already mentioned in my previous blog, JSON is the preferred input/output format but the documents are stored in BSON (Binary JSON) format in the database. So, here we will be using BsonDocument class object to store the data.
 
Create
  1. var things = db.GetCollection<BsonDocument>("things");  
  2.   
  3. //CREATE  
  4. BsonDocument personDoc = new BsonDocument();  
  5.   
  6. //Method 1  
  7. BsonElement personFirstNameElement = new BsonElement("PersonFirstName""Sankhojjal");  
  8. personDoc.Add(personFirstNameElement);  
  9.   
  10. //Method 2  
  11. personDoc.Add(new BsonElement("PersonAge", 23));  
  12.   
  13. things.InsertOne(personDoc);  
In this snippet, we retrieve the current collection first. Next, we create a BsonDocument object where we want to store our data. 
 
In Method 1, I showed how to explicitly create a BsonElement object variable to store key-value pair and then add it to the BsonDocument object.
 
In Method 2, I did not create a BsonElement object variable, rather I directly passed the object as parameter. The last statement inserts the data in the collection "things".
 
Read
  1. //READ  
  2. var resultDoc = things.Find(new BsonDocument()).ToList();  
  3. foreach (var item in resultDoc)  
  4. {  
  5.    Console.WriteLine(item.ToString());  
  6. }  
Update
  1. //UPDATE  
  2. BsonElement updatePersonFirstNameElement = new BsonElement("PersonFirstName""Souvik");  
  3.   
  4. BsonDocument updatePersonDoc = new BsonDocument();  
  5. updatePersonDoc.Add(updatePersonFirstNameElement);  
  6. updatePersonDoc.Add(new BsonElement("PersonAge", 24));  
  7.   
  8. BsonDocument findPersonDoc = new BsonDocument(new BsonElement("PersonFirstName""Sankhojjal"));  
  9.   
  10. var updateDoc = things.FindOneAndReplace(findPersonDoc, updatePersonDoc);  
  11.   
  12. Console.WriteLine(updateDoc);  
Delete 
  1. //DELETE  
  2. BsonDocument findPersonDoc = new BsonDocument(new BsonElement("PersonFirstName""Sourav"));  
  3.   
  4. things.FindOneAndDelete(findPersonDoc);  
The complete C# source code is given below.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using MongoDB.Driver;  
  7. using MongoDB.Bson;  
  8.   
  9. namespace ConsAppMongoDBCRUD  
  10. {  
  11.     class Program  
  12.     {  
  13.         static void Main(string[] args)  
  14.         {  
  15.             try  
  16.             {  
  17.                 MongoClient dbClient = new MongoClient("mongodb://127.0.0.1:27017");  
  18.   
  19.                 //Database List  
  20.                 var dbList = dbClient.ListDatabases().ToList();  
  21.   
  22.                 Console.WriteLine("The list of databases are :");  
  23.                 foreach (var item in dbList)  
  24.                 {  
  25.                     Console.WriteLine(item);  
  26.                 }  
  27.   
  28.                 Console.WriteLine("\n\n");  
  29.   
  30.                 //Get Database and Collection  
  31.                 IMongoDatabase db = dbClient.GetDatabase("test");  
  32.                 var collList = db.ListCollections().ToList();  
  33.                 Console.WriteLine("The list of collections are :");  
  34.                 foreach (var item in collList)  
  35.                 {  
  36.                     Console.WriteLine(item);  
  37.                 }  
  38.   
  39.                 var things = db.GetCollection<BsonDocument>("things");  
  40.   
  41.                 //CREATE  
  42.                 BsonElement personFirstNameElement = new BsonElement("PersonFirstName""Sankhojjal");  
  43.   
  44.                 BsonDocument personDoc = new BsonDocument();  
  45.                 personDoc.Add(personFirstNameElement);  
  46.                 personDoc.Add(new BsonElement("PersonAge", 23));  
  47.   
  48.                 things.InsertOne(personDoc);  
  49.   
  50.                 //UPDATE  
  51.                 BsonElement updatePersonFirstNameElement = new BsonElement("PersonFirstName""Souvik");  
  52.   
  53.                 BsonDocument updatePersonDoc = new BsonDocument();  
  54.                 updatePersonDoc.Add(updatePersonFirstNameElement);  
  55.                 updatePersonDoc.Add(new BsonElement("PersonAge", 24));  
  56.   
  57.                 BsonDocument findPersonDoc = new BsonDocument(new BsonElement("PersonFirstName""Sankhojjal"));  
  58.   
  59.                 var updateDoc = things.FindOneAndReplace(findPersonDoc, updatePersonDoc);  
  60.   
  61.                 Console.WriteLine(updateDoc);  
  62.   
  63.                 //DELETE  
  64.                 BsonDocument findAnotherPersonDoc = new BsonDocument(new BsonElement("PersonFirstName""Sourav"));  
  65.   
  66.                 things.FindOneAndDelete(findAnotherPersonDoc);  
  67.   
  68.                 //READ  
  69.                 var resultDoc = things.Find(new BsonDocument()).ToList();  
  70.                 foreach (var item in resultDoc)  
  71.                 {  
  72.                     Console.WriteLine(item.ToString());  
  73.                 }  
  74.             }  
  75.             catch (Exception ex)  
  76.             {  
  77.                 Console.WriteLine(ex.Message);  
  78.             }  
  79.   
  80.             Console.ReadKey();  
  81.         }  
  82.     }  
Very easy!!! Right?

That's it for now. I hope you liked it. Please stay tuned for more and keep coding!!!

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now