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.
- 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.
-
- var dbList = dbClient.ListDatabases().ToList();
-
- Console.WriteLine("The list of databases are :");
- foreach (var item in dbList)
- {
- Console.WriteLine(item);
- }
This code shows a list of databases present on the Server. Pretty easy, right?
Let's take a look at another one.
-
- IMongoDatabase db = dbClient.GetDatabase("test");
- var collList = db.ListCollections().ToList();
- Console.WriteLine("The list of collections are :");
- foreach (var item in collList)
- {
- Console.WriteLine(item);
- }
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
- var things = db.GetCollection<BsonDocument>("things");
-
-
- BsonDocument personDoc = new BsonDocument();
-
-
- BsonElement personFirstNameElement = new BsonElement("PersonFirstName", "Sankhojjal");
- personDoc.Add(personFirstNameElement);
-
-
- personDoc.Add(new BsonElement("PersonAge", 23));
-
- 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
-
- var resultDoc = things.Find(new BsonDocument()).ToList();
- foreach (var item in resultDoc)
- {
- Console.WriteLine(item.ToString());
- }
Update
-
- BsonElement updatePersonFirstNameElement = new BsonElement("PersonFirstName", "Souvik");
-
- BsonDocument updatePersonDoc = new BsonDocument();
- updatePersonDoc.Add(updatePersonFirstNameElement);
- updatePersonDoc.Add(new BsonElement("PersonAge", 24));
-
- BsonDocument findPersonDoc = new BsonDocument(new BsonElement("PersonFirstName", "Sankhojjal"));
-
- var updateDoc = things.FindOneAndReplace(findPersonDoc, updatePersonDoc);
-
- Console.WriteLine(updateDoc);
Delete
-
- BsonDocument findPersonDoc = new BsonDocument(new BsonElement("PersonFirstName", "Sourav"));
-
- things.FindOneAndDelete(findPersonDoc);
The complete C# source code is given below.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using MongoDB.Driver;
- using MongoDB.Bson;
-
- namespace ConsAppMongoDBCRUD
- {
- class Program
- {
- static void Main(string[] args)
- {
- try
- {
- MongoClient dbClient = new MongoClient("mongodb://127.0.0.1:27017");
-
-
- var dbList = dbClient.ListDatabases().ToList();
-
- Console.WriteLine("The list of databases are :");
- foreach (var item in dbList)
- {
- Console.WriteLine(item);
- }
-
- Console.WriteLine("\n\n");
-
-
- IMongoDatabase db = dbClient.GetDatabase("test");
- var collList = db.ListCollections().ToList();
- Console.WriteLine("The list of collections are :");
- foreach (var item in collList)
- {
- Console.WriteLine(item);
- }
-
- var things = db.GetCollection<BsonDocument>("things");
-
-
- BsonElement personFirstNameElement = new BsonElement("PersonFirstName", "Sankhojjal");
-
- BsonDocument personDoc = new BsonDocument();
- personDoc.Add(personFirstNameElement);
- personDoc.Add(new BsonElement("PersonAge", 23));
-
- things.InsertOne(personDoc);
-
-
- BsonElement updatePersonFirstNameElement = new BsonElement("PersonFirstName", "Souvik");
-
- BsonDocument updatePersonDoc = new BsonDocument();
- updatePersonDoc.Add(updatePersonFirstNameElement);
- updatePersonDoc.Add(new BsonElement("PersonAge", 24));
-
- BsonDocument findPersonDoc = new BsonDocument(new BsonElement("PersonFirstName", "Sankhojjal"));
-
- var updateDoc = things.FindOneAndReplace(findPersonDoc, updatePersonDoc);
-
- Console.WriteLine(updateDoc);
-
-
- BsonDocument findAnotherPersonDoc = new BsonDocument(new BsonElement("PersonFirstName", "Sourav"));
-
- things.FindOneAndDelete(findAnotherPersonDoc);
-
-
- var resultDoc = things.Find(new BsonDocument()).ToList();
- foreach (var item in resultDoc)
- {
- Console.WriteLine(item.ToString());
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- }
-
- Console.ReadKey();
- }
- }
- }
Very easy!!! Right?
That's it for now. I hope you liked it. Please stay tuned for more and keep coding!!!