MongoDb with C# – CRUD Operations Part 1

In this article we going to see about all important commands in mongodb with c# driver. I’m going to demonstrate a CRUD operations on MongoDb with C#, so it helps you to understand better.

Create a Sample Project in Visual Studio

Here I have created a project with namespace MongoDbEssentials.

To use MongoDb in Visual Studio C#, you have to install some necessary drivers.

Goto Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution -> Select Browse Tab

In the browse tab, type mongodb and select and install this below MongDb.Driver.

Click Install button

Once you installed it, you can verify it by clicking on the Dependencies -> Packages

Install Robo3T for GUI interface

To work with MongoDb in graphical user interface, you must install the Robo3T.

Download Link : https://robomongo.org/download

Connect to mongo server

List Databases

In my local server,I have five databases. So it displays like below,

List Collection content

In my MeiDatabase, I have a collection called entities, in that I have one document with one field “Name”.

Connect to Database and collection

Don’t give my database name(“MeiDatabase”) and collection name(“entities”), you have to give your own database and collection name.

using MongoDB.Driver;
using MongoDB.Bson;

using System;

namespace MongoDbEssesntials
{
    class Program
    {
        static void Main(string[] args)
        {
            //Connect to MongoServer
            MongoClient client = new MongoClient();

            //To Connect with Database
            var db = client.GetDatabase("MeiDatabase");

            //To connect with entities collection
            var entityCollection = db.GetCollection<Entity>("entities");

            var documents = entityCollection.AsQueryable().ToList();

            foreach (var document in documents)
                Console.WriteLine(document.Name);
           
        }
    }
    public class Entity
    {
        public ObjectId Id { get; set; }
        public string Name { get; set; }
    }
}


//Output: 

Tom

Create new database and new collection

Once you create database and collection and go and verify it in Robo3T.

InsertOne() in entities collection

using MongoDB.Driver;
using MongoDB.Bson;

using System;

namespace MongoDbEssesntials
{
    class Program
    {
        static void Main(string[] args)
        {
            //Connect to MongoServer
            MongoClient client = new MongoClient();

            //Get Database
            var db = client.GetDatabase("MeiDatabase");

            var collection = db.GetCollection<Entity>("entities");

            //Insert one name in entities collection
            collection.InsertOne(new Entity { Name = "Jerry" });
           
        }
    }
    public class Entity
    {
        public ObjectId Id { get; set; }
        public string Name { get; set; }
    }
}

You can see below, we have easily inserted Name : Jerry in entities collection.

InsertMany() in entities collection

using MongoDB.Driver;
using MongoDB.Bson;

using System;

namespace MongoDbEssesntials
{
    class Program
    {
        static void Main(string[] args)
        {
            //Connect to MongoServer
            MongoClient client = new MongoClient();

            //Get Database
            var db = client.GetDatabase("MeiDatabase");

            var collection = db.GetCollection<Entity>("entities");

            string[] names = new string[] { "Jackiechan", "July", "Popey", "Beem", "Dora" };
          
            Entity[] entities = new Entity[5];

            for(int i = 0; i < entities.Length; i++)
            {
                entities[i] = new Entity();
                entities[i].Name = names[i];
            }

            //Insert Many names in collection
            collection.InsertMany(entities);
           
        }
    }
    public class Entity
    {
        public ObjectId Id { get; set; }
        public string Name { get; set; }
    }
}

In this article, we seen about how to connect with mongo database, create collection, get collection and insert commands.

In my next article, I will demonstrate about Find, Retrieve, Update, Delete commands with detailed explanations.

In coming week, Part 2 of the article will be released. Stay tuned.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s