Click here to Skip to main content
15,867,308 members
Articles / Programming Languages / C#

Using MongoDB with C# driver

Rate me:
Please Sign up or sign in to vote.
4.75/5 (18 votes)
8 Aug 2015CPOL4 min read 78.3K   2.2K   31   17
In this blog post, we will understand how to use MongoDB as backend service for our .NET application using C# drivers.

Introduction

As we know, MongoDB is a NoSQL (i.e. non-relational) database, which is an open source DBMS stores data in form of documents with JSON format. NoSQL databases provide high performance and it is easy to maintain in comparison to any RDBMS (Relational Database Management System) when we have to deal with unstructured data for our application.

Configure MongoDB & Robomongo

To use MongoDB within our .NET application, first we need to install MongoDB and Robomongo (Free GUI tool to use MongoDB) into our system. This is very easy process to install, configure and use MongoDB.

Steps to Configure MongoDB

  1. First, we have to download MongoDB. While downloading it, make sure we choose the correct version for Windows (i.e., download should fit our system configuration, as for Windows 8 on a 64 bit processor, we need “64 bit 2008 R2+”). Using msi file, we need to install MongoDB.
  2. Make entry inside environment variables (PATH variable):
    C#
    C:\Program Files\MongoDB\Server\3.0\bin\
  3. Default installation location for this will be:
    C#
    C:\Program Files\MongoDB\Server\3.0
  4. Create a folder named MongoDB at any location (prefer to create at root level):

    For example: D:\MongoDB

  5. In the folder created above, we need to create a folder “data” and inside data folder, create another folder “db”. 
  6. Inside MongoDB folder, create a text file, name it “mongod.cfg” and paste the following code there:
    dbpath = D:\MongoDB\data\db
    
    logpath = D:\MongoDB\mongod.log
    
    logappend = true

    Note: dbpath & logpath can be changed as per path for MongoDBfolder in system

  7. Create window service, run the command prompt as “Run as administrator”. Go to the path to bin folder of MongoDB in our system (i.e. C:\Program Files\MongoDB).
  8. Run the following command:
    C#
    sc.exe create MongoDB binPath= "C:\Program Files\MongoDB\Server\3.0\bin\mongod.exe 
    --service --config=\"D:\MongoDB\mongod.cfg\"" DisplayName= "MongoDB" start= "auto"

    After this, MongoDB is up and running on our system as a service.

    Image 1

Steps to Configure Robomongo(GUI tool)

  1. First, download robomongo and install it into your system.
  2. Start robomongo tool and try to configure database. Inside MongoDB connection wizard, click “create” link to establish connection.

    Image 2

Let’s Start Some Coding

Up to this point, we have MongoDB and Robomongo installed into our system. Now this is the time to use MongoDB as DBMS for our application using C# drivers.

  1. Make sure Visual Studio is installed into the system. Open Visual Studio and create a sample console application, name it: “LibraryApplication”.
  2. The second step is to install official mongoDB C# drivers’ packages from nuget store. Go to online nuget packages and type “mongo”. Install both drivers for application.

    Image 3

  3. Check this step will install few DLLs into the application:

    Image 4

    MongoDB.Bson DLL deals with BSON document of MongoDB and provides information how to serialize data from that document.

  4. The first thing that I am going to create a class for our LibraryApplication project:
    C#
    public class BookStore
    {
       public ObjectId Id { get; set; }
       public string BookTitle { get; set; }
       public string Auther { get; set; }
       public string Category { get; set; }
       public string ISBN { get; set; }
    }
    

    Here, notice I have created one property with type “ObjectId” and name “Id”. This is the unique identification for a document in MongoDB. We can have this type with any other unique property as well. In fact, if we will not create any of such property in class, then MongoDB by default creates the same with name _Id, to uniquely identify that document.

  5. The other step is to establish connection to database (MongoDB) and try to insert data to our database.
    C#
    static void Main(string[] args)
    {
                MongoClient client = new MongoClient();
                var server = client.GetServer();
                var db = server.GetDatabase("LibraryDB");
                var collection = db.GetCollection<BookStore>("BookStore");
    
                BookStore bookStore = new BookStore
                {
                    BookTitle = "MongoDB Basics",
                    ISBN = "8767687689898yu",
                    Auther = "Tanya",
                    Category = "NoSQL DBMS"
                };
    
               collection.Save(bookStore);
     }
    1. Check the first line of code, “MongoClient” is used to create a connection to MongoDB. We can also specify the connection string (with server name, port, etc.) to this object. For now, I am connecting to local database server with default port, so we don’t need to provide connection string argument here.
    2. Next line is to get the server connected.
    3. Once server has been connected, then we have to get the database.
    4. Next is to create a collection (can be thought of as a table in RDBMS) and save data into it.
  6. After executing the program, we can see the magic:

    Image 5

    In our database, a new database named “LibraryDB” has been created with collection “BookStore” and data inserted in it.

    Important feature here is, it will create new database if it does not exist and update if it already exists. Same is with collections.

    For example, if we add another record into a collection:

    C#
    BookStore bookStore = new BookStore
    {   
       BookTitle = "C# Basics",
       ISBN = "27758987689898yu",
       Auther = "Somya",
       Category = "Programming Languages"
    }            

    This will add one more document to existing “Bookstore“ collection.

  7. One more important thing is, as I told earlier, we can also set any of our property as unique identification like this:
    C#
    [BsonId]
    string ISBN { get; set; }

    Run the application and check, now ISBN number will act as unique identification for document. There will not be any field name ISBN in database in this case.

    Image 6

  8. We can have nullable fields in MongoDB and that is not shown in document if value is null:
    C#
    [BsonIgnoreIfNull]
    public int? TotalPages { get; set; }

    Image 7

  9. Now let’s query the data from database:
    C#
    //To get books count having pages more than 200
    bookCount = collection.AsQueryable().Where(b => b.TotalPages > 200);
    
    //To get Book having title starts with 'Mongo’
    collection.AsQueryable().Where(b => b.BookTitle.StartsWith("Mongo"));
    
    //To get Cheapest Book
    collection.AsQueryable().OrderBy(b => b.Price).First();
    
    //To get book with a particular ISBN number
    collection.AsQueryable().Single(b => b.ISBN == "27758987689898yu");
    
    //To remove all collections
    collection.RemoveAll();

Summary

So in this article, we understood how to use MongoDB in our .NET applications using C# drivers, how we can insert/query data from MongoDB using C# code.

Please stay tuned for more information on MongoDB usage.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) 3Pillar Global Pvt. Ltd.
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionUse mongo csharp driver with View Pin
deelll27-Oct-19 8:57
deelll27-Oct-19 8:57 
PraiseConfigure MongoDB Pin
akisingh12-Dec-16 19:59
akisingh12-Dec-16 19:59 
Nice article. it is very useful for the developer.

I have followed the Steps to Configure MongoDB

I configured below path
F:\MongoDB\data\db
F:\MongoDB\mongod.log

but both folder is empty. i followed all step. can you please suggest me what i am missing?
QuestionVisual Studio version? Pin
Emre Ataseven27-Jan-16 6:07
professionalEmre Ataseven27-Jan-16 6:07 
Question5 out of 5 Pin
Shyam S Singh8-Jan-16 1:33
Shyam S Singh8-Jan-16 1:33 
GeneralMy vote of 5 Pin
Meenakshi Kumar8-Jan-16 0:46
Meenakshi Kumar8-Jan-16 0:46 
Question5 out of 5 Pin
Shyam S Singh8-Jan-16 0:45
Shyam S Singh8-Jan-16 0:45 
GeneralGood Work Pin
Alireza_136227-Dec-15 7:44
Alireza_136227-Dec-15 7:44 
PraiseReally nice article :) Pin
Member 30242829-Dec-15 3:22
Member 30242829-Dec-15 3:22 
QuestionNot working Pin
GerhardKreuzer28-Aug-15 20:45
GerhardKreuzer28-Aug-15 20:45 
QuestionTransactions Pin
GerhardKreuzer16-Aug-15 7:11
GerhardKreuzer16-Aug-15 7:11 
QuestionTypo ?? Pin
GerhardKreuzer14-Aug-15 0:16
GerhardKreuzer14-Aug-15 0:16 
AnswerRe: Typo ?? Pin
Tanya Jain(Dev)14-Aug-15 0:49
professionalTanya Jain(Dev)14-Aug-15 0:49 
GeneralRe: Typo ?? Pin
GerhardKreuzer14-Aug-15 1:32
GerhardKreuzer14-Aug-15 1:32 
GeneralAwesome.. Pin
Member 302428210-Aug-15 2:54
Member 302428210-Aug-15 2:54 
QuestionWhich driver version are you using? Pin
truc binh10-Aug-15 0:51
truc binh10-Aug-15 0:51 
AnswerRe: Which driver version are you using? Pin
Tanya Jain(Dev)10-Aug-15 1:01
professionalTanya Jain(Dev)10-Aug-15 1:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.