How to Connect a Mongo DB Server Through C# .Net Using C# Driver


In this article I will describe how to connect a Mongo db server in C#.Net and after that how to create the collection in the Mongo db.

Before beginning the coding, as we all know we have to open the "mongogod.exe" application.

Step 1: First create a console application named "Mongocreateserver".

Step 2:

After that paste the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MongoDB.Driver;
using MongoDB.Bson;
using System.Collections;
using MongoDB.Bson.Serialization;
using MongoDB.Driver.Builders;
using MongoDB;

namespace mongocreateserver
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = "mongodb://192.168.40.27";
            var server = MongoServer.Create(connectionString);
            if (server.State == MongoServerState.Disconnected)
                server.Connect();
            var OneConsoleDB = server.GetDatabase("One");
            if (!OneConsoleDB.CollectionExists("NextMessages"))
                OneConsoleDB.CreateCollection("NextMessages", null);
            var NextMessages = OneConsoleDB.GetCollection("NextMessages");
            server.Disconnect();
            Console.WriteLine("Server get connected in to this" + connectionString + "Server");
            server.GetDatabaseNames();
            server.Disconnect();
            Console.ReadLine();
        }
    }
}

See here we are defining the connection string.

After that we are creating the server with the connection string which means specify my system IP.

After that we are creating the server connection.

Then we are creating the Database named "One".

After that we are creating the collection name "NextMessages".

Finallly we are disconnecting from the server.

So when we run the application it will look like:

Severconenctinmongodb.jpg
 
Conclusion:

So in this article we have seen how to create a connection to the Mongo db and after that create the collection in that Mongo db.

Up Next
    Ebook Download
    View all
    Learn
    View all