MongoDB With C#

MongoDB with C#

MongoDB is a scalable, open source, high performance, document oriented database. Developed and supported by the company 10Gen, it is written in C++. 

NoSQL is a new trend in database development and refers generally to databases without a fixed schema. MongoDB is one of the newer NoSQL databases developed in 2009. Due to this dynamic schema, MongoDB is highly fit for the solution that follows agile methodology, in other words we will have a definitive deliverable in each sprint. Where our new releases should not affect another already operational database and schema.

Installing MongoDB on Windows you can follow this link Those with a SQL background can have look here for basic queries from SQL to MongoDB in
We can use MongoDB as a backend for the applications written in C#. For the same we need to have a C# Driver that connect to MongoDB. For more details on C# Driver you can have look at C# driver for MongoDB.

Once we have connected to MongoDB using the C# driver, we can query MongoDB collections and documents from C# using LINQ. For further details LINQ queries for MongoDB.

So here I will describe the basics of working with MongoDB using C#. This article is intended for readers with a basic knowledge of MongoDB and C#.

MongoDB Security

We can run MongoDB with and without credentials, in other words we can run mongod.exe using command prompt (Run as Administrator) as below.

Here we are running mongod.exe using the "--auth" keyword, in other words MongoDB is running with authentication and authorization.


Figure 1

Once we run MongoDB with authorization we need to provide a User Name and Password to connect to a specific DB. So prior to running with authorization we run without authorization and add user credentials for a specific DB.

Once we run mongod.exe, to work with MongoDB we can use mongoShell scripts "mongo.exe". In the following Figure-2, I am running mongo.exe and choosing the specific database and adding the user credentials for that db. Here we have many options for providing roles.


Figure 2

Once we have added user credentials for the DB, we re-run mongod.exe as in Figure-1 with  the "--auth" keyword.

Once we run MongoDB with authorization (--auth) we cannot access MongoDB without credentials. So we need to connect to MongoDB using db.auth keyword as in Figure-3.


Figure 3

MongoDB with C#

Here I am making a sample collaborative MVC 4 application in C# using MongoDB. Using Visual Studio, create a new MVC4 web application ("File" -> "New" -> "Project..." -> "ASP.NetMVC-4 Web application").

Download C# driver

To connect to MongoDB from C# , we need to have a C# driver to connect to MongoDB.

For downloading the C# driver we can use the Package Manager Console in VisualStudio.

"Tools" => "Library Package Manager" => "Package Manager Console"

On the Package Manager Console type "Install-Package mongocsharpdriver".


Now if we check our project references, we will see two new DLLs added as a package and referred to.

The C# driver consists of the two libraries MongoDB.Bson.dll and MongoDB.Driver.dll.

In these two libraries some of the important classes and methods I am briefing below that I used in my sample application.

The important classes of BSON object models are: BsonType, BsonValue, BsonElement, BsonDocument. Here the Bson library handles all BSON specifications, serializations, BSON documents, BSON array, etc.

BsonElement: name/value pair, where value is the bson value. It is the building block of a Bson Document.

BsonDocument: name/value pair collections (represented by the BSON element). It is an in-memory object model of a BSON document.

Important classes of Driver Object


  • MongoClient class: Root object of working with MongoDB.
  • MongoServer class: Has the GetDataBase() method, by which we can get a server instance
  • MongoDataBase class: has the GetCollection() method that returns an object representing a collection in the data base.
  • MongoCollection class: Represents a collection in a MongoDB data base. It has varios methods to work with the collection, such as Insert(), Save(), FindOne(), FindOneAs(), Update(), Remove() etc.

Connect to MongoDB in C# with Credentials

            var credential = MongoCredential.CreateMongoCRCredential("MongoTwitter""myadmin""pass@123");
//Server settings
            var settings = new MongoClientSettings
                Credentials = 
new[] { credential },
                Server = 
new MongoServerAddress("")
//Get a Reference to the Client Object
            mongoClient = new MongoClient(settings);
            mongoServer = mongoClient.GetServer();

Connect to MongoDB in C# without credentials

#region Without Credentials
//Specify Connection string

 connectionString = "mongodb://localhost";
 mongoClient = new MongoClient(connectionString);
mongoServer = mongoClient.GetServer();