Over a million developers have joined DZone.

Using MongoDB via .NET

· Database Zone

Learn NoSQL for free with hands-on sample code, example queries, tutorials, and more.  Brought to you in partnership with Couchbase.

Objective :

In this post i will explain how can we interact with data residing in MongoDB using .Net.

Ingredients :

Mongodb-win32-i386-2.2.3 , Microsoft Windows Vista Professional, Visual Studio 2010

Recipe :

Setting up MongoDB

Configure Mongodb.  Make sure you make a “Data\db” directory at drive
Root where your MongoDB (Mongodb-win32-i386-2.2.3) folder.  The MongoDB
System will store all its data under “Data\db“.

For convenience I re-named this(Mongodb-win32-i386-2.2.3)) to MongoDB only, It helps later when we use the command prompt. ( with shorter name )

Open a command line console, navigate to to MongoDb\bin  & run mongod, ( primary process to connect with MongoDB server instance )

Open a new command line console, navigate to to MongoDb\bin  & run mongo, ( a shell interface to MongoDB )

*Our shell interface should be connected to server listening on port 27017 ( default port )

.NET code

MongoDB Team provides Several driver to connect with MongoDB System.  Download C# driver.

Open Visual Studio 2012 , create new windows forms application.

Add project Reference to MongoDB.Driver.dll

Form1

Go to code behind & add namespaces

# region MongoRefs

using MongoDB;

using MongoDB.Driver;

using MongoDB.Driver.Linq;

using MongoDB.Driver.Builders;

#endregion

I used following code to insert some dummy data in our mongodb datastore.

MongoServer mongoServer = MongoServer.Create();

mongoServer.Connect();

MongoDatabase mDB = mongoServer.GetDatabase(“Analytics”);

MongoCollection mCollection = mDB.GetCollection<DemoStats>(“DemoStats”);

 #region Populate manual data

if (mCollection.Count() == 0)

{

DemoStats objDemoStat = new DemoStats() {
SpeakerName = “Sarfraz”, Id = Guid.NewGuid().ToString(), Topic =
“Demonstrating MongoDB & Twitter with Web API”, AudienceCount = “11″
};

mCollection.Save(objDemoStat);

 objDemoStat = new DemoStats() {
SpeakerName = “Asif”, Id = Guid.NewGuid().ToString(), Topic = “Overview
Microsoft Dynamics CRM”, AudienceCount = “13″ };

mCollection.Save(objDemoStat);

 objDemoStat = new DemoStats() {
SpeakerName = “Fahad”, Id = Guid.NewGuid().ToString(), Topic = “OData
Services with WCF Data Services”, AudienceCount = “15″ };

mCollection.Save(objDemoStat);

 }

#endregion

You can now see via Mongo Console how our data looks like.

MongoConsole

I used following code to retrieve/query database records

#region Retrieve Data from Mongo

if (Convert.ToInt32(mCollection.GetStats().ObjectCount) > 0)

{

var demoData = mCollection.FindAs(typeof(DemoStats), Query.EQ(“SpeakerName”, txtSpeakerName.Text));

if (demoData.Count() > 0)
{
foreach (DemoStats objStat in demoData)
{
lblTopic.Text = Convert.ToString(objStat.Topic);
lblAudienceCount.Text = Convert.ToString(objStat.AudienceCount);
}

lblMessage.Text = “Match Found”;
}
else
{
lblMessage.Text = “Match Not Found”;
}
}
else
{
lblMessage.Text = “No Records Found”;
}
#endregion

In the end, make sure your code disconnects from the Mongo Instance
mongoServer.Disconnect();

Delicious Coding!

The Getting Started with NoSQL Guide will get you hands-on with NoSQL in minutes with no coding needed. Brought to you in partnership with Couchbase.

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}