Friday, 30 June 2017

MongoDB with C#

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!!!

Saturday, 24 June 2017

Introduction to MongoDB

Hello everyone. After a long time, again I am starting a new part of my blogs.
This part will involve about getting started with MongoDB in C# for the
beginners. This will include basic introduction to NoSQL, MongoDB, a C#
console application
and Azure CosmosDB. Don't wanna bore you with just
infos. So let's get started.

First of all, what is NoSQL? NoSQL (originally referring to "non SQL",
"non relational" or "not only SQL") is a query language which uses a different
mechanism of storage and retrieval of data in non-relational databases,
unlike the tabular relations used in relational databases. NoSQL stores data
in a key-value pair. A simplest example of NoSQL would be like :
{ "FirstName" : "Alex", "Age" : 25, "Email" : "alex@gmail.com" }
Wait a second! This example rings a bell, isn't it? It looks just like
JSON data. You are absolutely right. Most of the non-relational databases
use JSON as their preferred input/output format. If you don't have the
knowledge of JSON, no worries. Just study a little bit about JSON and you
will be ready to go.

Next is the platform where these NoSQL statements will be executed.
Like SQL statements are executed in the relational databases like
Microsoft SQL Server, Oracle, MySQL, etc. Similarly, NoSQL statements
are executed in non-relational databases like MongoDB, RavenDB,
CouchDB, DocumentDB, etc. In our blog, we will be focusing on MongoDB.
Before getting started with MongoDB, you might wanna know when and
where to use NoSQL. Although, this question is quite debatable.
Still, you can refer to Ted Neward's Blog which will clear out
some mist.

MongoDB (from humongous) is a free and open source database,
published under the GNU Affero General Public License which
stores data in a document-oriented format. MongoDB uses
JSON-like documents with schemas. It stores the data in the
BSON (Binary JSON) form in the database. But uses JSON as
preferred input/output format.



As mentioned earlier, MongoDB is free and open source software
which can be easily downloaded from the official website.
Just download the Community Server edition MSI installer
for Windows and install.



Once installed, you need to verify whether everything works
fine or not. By default, MongoDB wants to store data in the
default file system path, C:\data\db, but this is configurable
with a text file passed by name on the command line via --config.
Again by default, C:\data\db directory won't exist and
installing MongoDB won't create this directory. You have to
manually create this directory or configure the system path to
your preferred directory. If you don't do it, the MongoDB server
won't work properly. Let's not get into the hassle with
configurable system path and keep it simple with the
default system path.

Now open up command prompt by pressing Windows + R keys and type
cmd and press Enter. Navigate to the directory
"C:\Program Files\MongoDB\Server\3.4\bin" by executing these
commands :

cd ..\..
cd "C:\Program Files\MongoDB\Server\3.4\bin"



If you navigate to this directory in terms of folder view,
you will notice a bunch of files out of which you need only
two executable files to get you started - mongod.exe and
mongo.exe.

The mongod.exe is the database process itself and the
mongo.exe is the command-line client for executing
NoSQL statements.

Now in the command prompt, type "mongod.exe" and press Enter.



If the the text "waiting for connections on port 27017"
comes up, you will know the MongoDB server is up and running.
Minimize this command prompt window and open up another
command prompt window. Navigate to the same directory
"C:\Program Files\MongoDB\Server\3.4\bin" and fire up "mongo.exe".



This is the client for executing NoSQL commands.

So, let's start writing few commands for better understanding.

1. db.adminCommand( { listDatabases: 1 } )
This command displays the list of databases in MongoDB Server.
The default database is "test".



2. db.getCollectionNames()
This command displays the list of collection in the current database.
The default collection is "things".



Here, you can think of collection as table.

These are more database related commands. For further details,
you can refer to this link.

3. p1 = {"PersonFirstName":"Alex","PersonAge":28}
    db.things.save(p1)

The first command creates a temporary document p1 which contains
the actual data to be stored in the collection "things".
Here, document is not a file, like word(.docx) file,
text(.txt) file, etc. Rather it refers to the row/tuple
that contains the data. The keys ("PersonFirstName" or "PersonAge")
in it are known as elements of the document.
The second command actually stores p1 temporary document in the
collection "things" permanently.



4. db.things.find()
This command displays the list of documents in the
collection "things" (a maximum count of 20 documents).



Here, you notice that there is another element "_id" that
you didn't create. It is auto-generated for uniquely
identifying the document. You can think of it as
"Primary Key".

5. findP = {"PersonFirstName":"Alex"}
    db.things.find(findP)

This command displays the specific document with the passed
parameters.



6. testP = {"PersonAge":28}
    setP = {"PersonFirstName":"Brandt"}
    db.things.updateOne(testp,{ $set : setp })

This command updates the element "PersonFirstName" from "Alex"
to "Brandt" of the specific document with the "PersonAge" as 28.



7. db.things.deleteOne(testP)
This command deletes the specific document.



These are the basic CRUD operation commands. For more details,
you can refer to this link.

Now to close the mongo.exe client, type "exit" and press Enter.
Close this window.
Again to close mongod.exe process, press Ctrl + C.

That's all.  I hope this blog helps you to get started with MongoDB.
Till then, stay tuned. Keep Coding!!!