Hello everyone. In my previous blog, you got a little knowledge
of MongoDB basics. This blog will focus on doing CRUD operations
from a C# console application. The working mechanism will be
same for web applications and desktop applications.
Open up the 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 the 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" and press Ctrl + . and press Enter
to add the namespace "MongoDB.Drivers".
Now let's try to execute some database commands.
//Database List
var dbList = dbClient.ListDatabases().ToList();
Console.WriteLine("The list of databases are :");
foreach (var item in dbList)
{
Console.WriteLine(item);
}
This code shows the list of database present in the server.
Pretty easy, right? Let's take a look on another one.
//Get Database and Collection
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.
1. Create :
var things = db.GetCollection<BsonDocument>("things");
//CREATE
BsonDocument personDoc = new BsonDocument();
//Method 1
BsonElement personFirstNameElement = new BsonElement("PersonFirstName", "Sankhojjal");
personDoc.Add(personFirstNameElement);
//Method 2
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".
2. Read :
//READ
var resultDoc = things.Find(new BsonDocument()).ToList();
foreach (var item in resultDoc)
{
Console.WriteLine(item.ToString());
}
3. Update :
//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);
4. Delete :
//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");
//Database List
var dbList = dbClient.ListDatabases().ToList();
Console.WriteLine("The list of databases are :");
foreach (var item in dbList)
{
Console.WriteLine(item);
}
Console.WriteLine("\n\n");
//Get Database and Collection
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");
//CREATE
BsonElement personFirstNameElement = new BsonElement("PersonFirstName", "Sankhojjal");
BsonDocument personDoc = new BsonDocument();
personDoc.Add(personFirstNameElement);
personDoc.Add(new BsonElement("PersonAge", 23));
things.InsertOne(personDoc);
//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 findAnotherPersonDoc = new BsonDocument(new BsonElement("PersonFirstName", "Sourav"));
things.FindOneAndDelete(findAnotherPersonDoc);
//READ
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 this blog. I hope you enjoyed it.
Till then stay tuned and keep coding!!!
of MongoDB basics. This blog will focus on doing CRUD operations
from a C# console application. The working mechanism will be
same for web applications and desktop applications.
Open up the 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 the 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" and press Ctrl + . and press Enter
to add the namespace "MongoDB.Drivers".
Now let's try to execute some database commands.
//Database List
var dbList = dbClient.ListDatabases().ToList();
Console.WriteLine("The list of databases are :");
foreach (var item in dbList)
{
Console.WriteLine(item);
}
This code shows the list of database present in the server.
Pretty easy, right? Let's take a look on another one.
//Get Database and Collection
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.
1. Create :
var things = db.GetCollection<BsonDocument>("things");
//CREATE
BsonDocument personDoc = new BsonDocument();
//Method 1
BsonElement personFirstNameElement = new BsonElement("PersonFirstName", "Sankhojjal");
personDoc.Add(personFirstNameElement);
//Method 2
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".
2. Read :
//READ
var resultDoc = things.Find(new BsonDocument()).ToList();
foreach (var item in resultDoc)
{
Console.WriteLine(item.ToString());
}
3. Update :
//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);
4. Delete :
//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");
//Database List
var dbList = dbClient.ListDatabases().ToList();
Console.WriteLine("The list of databases are :");
foreach (var item in dbList)
{
Console.WriteLine(item);
}
Console.WriteLine("\n\n");
//Get Database and Collection
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");
//CREATE
BsonElement personFirstNameElement = new BsonElement("PersonFirstName", "Sankhojjal");
BsonDocument personDoc = new BsonDocument();
personDoc.Add(personFirstNameElement);
personDoc.Add(new BsonElement("PersonAge", 23));
things.InsertOne(personDoc);
//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 findAnotherPersonDoc = new BsonDocument(new BsonElement("PersonFirstName", "Sourav"));
things.FindOneAndDelete(findAnotherPersonDoc);
//READ
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 this blog. I hope you enjoyed it.
Till then stay tuned and keep coding!!!




No comments:
Post a Comment