Click here to Skip to main content
Click here to Skip to main content

Connecting to MongoDB using C#

By , 30 Apr 2013
 

Introduction

MongoDB is an open source document-oriented database system developed and supported by 10gen. It is part of the NoSQL family of database systems. Instead of storing data in tables as is done in a "classical" relational database, MongoDB stores structured data as JSON-like documents with dynamic schemas (MongoDB calls the format BSON), making the integration of data in certain types of applications easier and faster.

Binaries are available for Windows, Linux, OS X, and Solaris.

Main Features

The following is a brief summary of some of the main features:

Ad Hoc Queries

MongoDB supports search by field, range queries, regular expression searches. Queries can return specific fields of documents and also include user-defined JavaScript functions.

Indexing

Any field in a MongoDB document can be indexed (indices in MongoDB are conceptually similar to those in RDBMSes). Secondary indices are also available.

Replication

MongoDB supports master-slave replication. A master can perform reads and writes. A slave copies data from the master and can only be used for reads or backup (not writes). The slaves have the ability to select a new master if the current one goes down.

Load Balancing

MongoDB scales horizontally using sharding. The developer chooses a shard key, which determines how the data in a collection will be distributed. The data is split into ranges (based on the shard key) and distributed across multiple shards. (A shard is a master with one or more slaves.)

MongoDB can run over multiple servers, balancing the load and/or duplicating data to keep the system up and running in case of hardware failure. Automatic configuration is easy to deploy and new machines can be added to a running database.

File Storage

MongoDB could be used as a file system, taking advantage of load balancing and data replication features over multiple machines for storing files.

This function, called GridFS, is included with MongoDB drivers and available with no difficulty for development languages (see "Language Support" for a list of supported languages). MongoDB exposes functions for file manipulation and content to developers. GridFS is used, for example, in plugins for NGINX. And lighttpd.

In a multi-machine MongoDB system, files can be distributed and copied multiple times between machines transparently, thus effectively creating a load balanced and fault tolerant system.

Aggregation

MapReduce can be used for batch processing of data and aggregation operations. The aggregation framework enables users to obtain the kind of results for which the SQL GROUP BY clause is used.

Server-side JavaScript Execution

JavaScript can be used in queries, aggregation functions (such as MapReduce), are sent directly to the database to be executed.

Capped Collections

MongoDB supports fixed-size collections called capped collections. This type of collection maintains insertion order and, once the specified size has been reached, behaves like a circular queue.

Prerequisites

  • Install Visual Studio 2010 or Visual Studio 2012
  • Click here to download MongoDB
  • Click here to download the latest MongoDB C# driver

Set up the MongoDB Environment

After downloading MongoDB, Extract the archive to C:\ by right clicking on the archive and selecting Extract All and browsing to C:\.

Note: The folder name will be either:

C:\mongodb-win32-i386-[version] 

Or:

C:\mongodb-win32-x86_64-[version] 

In both examples, replace [version] with the version of MongoDB downloaded.

Using Command prompt, run the following code:

cd \ 
move C:\mongodb-win32-* C:\mongodb 

MongoDB requires a data folder to store its files. The default location for the MongoDB data directory is C:\data\db. Create this folder using the Command Prompt. Issue the following command sequence:

md data 
md data\db 

Note: You may specify an alternate path for \data\db with the dbpath setting for mongod.exe, as in the following example:

C:\mongodb\bin\mongod.exe --dbpath d:\test\mongodb\data 

If your path includes spaces, enclose the entire path in double quotations, for example:

C:\mongodb\bin\mongod.exe --dbpath "d:\test\mongodb data" 

Start MongoDB

To start MongoDB, execute from the Command Prompt:

C:\mongodb\bin\mongod.exe 

This will start the main MongoDB database process. The waiting for connections message in the console output indicates that the mongod.exe process is running successfully.

Getting Started

Step 1

Execute the below line using Command prompt:

C:\mongodb\bin\mongod.exe --dbpath "d:\test\mongodb\data" 

Output

Step 2

Add Reference MongoDB C# drivers into project:

MongoDB.Bson.dll 
MongoDB.Driver.dll 
MongoDB.GridFS.dll 
MongoDB.Linq.dll 

Step 3

Create Console application and paste the below codes:

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

namespace MongoDB
{
    class Program
    {
        static void Main(string[] args)
        {
            var mongo = new Mongo();
            mongo.Connect();
            var db = mongo.getDB("testmongo");
            var categorylist = db.GetCollection("studcategories");
            var category = new Document();
            category["Name"] = "Govardhan";
            category["Id"] = "5";
            category["Adress"] = "Mysore";

            categorylist.Insert(category);

            Console.WriteLine("Total number of data is:-" + categorylist.Count());

            var categories = db.GetCollection("studcategories").FindAll().Documents;
            foreach (var lstcategory in categories)
            {
                Console.WriteLine(lstcategory["Name"]);
                Console.WriteLine(lstcategory["Id"]);
                Console.WriteLine(lstcategory["Adress"]);
            }
            Console.WriteLine("press enter to delete the records");
            categorylist.Delete(category);
            Console.ReadLine(); 
        }
    }
}

Output

License

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

About the Author

Ravindra T C
Software Developer Marlabs Software Pvt Ltd, Mysore
India India
Member
I'm a software developer. I spent most of the time in learning new technologies. I've a keen interest in client-side technologies especially JavaScript and Jquery it is the most beautiful language ever seen.

I like sharing my knowledge and written some non-popular articles. I believe in quality and standards but blames myself for lagging them.

I believe in small things and they makes me happy!

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 1member ProgramFOX12 May '13 - 6:12 
GeneralMy vote of 3memberSagarJaybhay11 May '13 - 18:11 
QuestionCan installing Mongo be automated ?memberBillWoodruff28 Apr '13 - 19:41 
AnswerRe: Can installing Mongo be automated ?memberephy_l29 Apr '13 - 21:39 

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130513.1 | Last Updated 30 Apr 2013
Article Copyright 2013 by Ravindra T C
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid