C# and MongoDB

So with my MongoDB server running it was time to write some code against it to create collections, add documents to it, update, delete etc

Downloaded the C# driver, fired up VS 2010 and wrote some code

A simple winform app which on load connected to the db “test” and got the collection “books” and then buttons to create “documents” (one at a time and in a batch), read “documents” (top one and all), dropping all documents, updating based on a condition and removing one document from a collection.

Form

Here is the code…

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MongoDB.Bson;
using MongoDB.Driver;

namespace FirstMongoApp
{
public partial class Form1 : Form
{

MongoDatabase database;
MongoCollection<BsonDocument> books = null;

public Form1()
{
InitializeComponent();
}

//Write records to a table…errr Collection!!!
private void button1_Click(object sender, EventArgs e)
{

books = database.GetCollection<BsonDocument>(“books”);

BsonDocument book = new BsonDocument {
{ “author”, “Ernest Hemingway” },
{ “title”, “For Whom the Bell Tolls” },
{ “rating”, “5.1” }
};
books.Insert(book);

book = new BsonDocument {
{ “author”, “Bad Hemingway” },
{ “title”, “Bad Bell Tolls” },
{ “price”, “9.99” }
};
books.Insert(book);

BsonDocument[] batch = {
new BsonDocument {
{ “author”, “Kurt Vonnegut” },
{ “title”, “Cat’s Cradle” }
},
new BsonDocument {
{ “author”, “Kurt Vonnegut” },
{ “title”, “Slaughterhouse-Five” }
}
};
books.InsertBatch(batch);
}
//Initialize
private void Form1_Load(object sender, EventArgs e)
{
var connectionString = “mongodb://localhost”;
var client = new MongoClient(connectionString);
var server = client.GetServer();
database= server.GetDatabase(“test”); // WriteConcern defaulted to Acknowledged

books = database.GetCollection<BsonDocument>(“books”);

}

//Read one
private void button2_Click(object sender, EventArgs e)
{
BsonDocument doc = books.FindOne();

if (!(doc == null))
{
foreach (BsonElement element in doc.Elements)
{
MessageBox.Show(element.Name + ” ” + element.Value);

}
}
}

//Read all
private void button4_Click(object sender, EventArgs e)
{
if (!(books == null))
{
var docs = books.FindAll();
foreach (var book in docs)
{
foreach (BsonElement element in book.Elements)
{
MessageBox.Show(element.Name + ” ” + element.Value);

}
}
}

}

//Delete al
private void button3_Click(object sender, EventArgs e)
{
if (!(books == null))
{
books.Drop();
}

}

//Update
private void button5_Click(object sender, EventArgs e)
{
var query = new QueryDocument{
{ “author”, “Kurt Vonnegut” }
};
var update = new UpdateDocument {
{ “$set”, new BsonDocument(“title”, “Cat’s Kradle”) }
};
books.Update(query, update);
query = new QueryDocument{
{ “author”, “Bad Hemingway” }
};
update = new UpdateDocument {
{ “$set”, new BsonDocument(“title”, “Cat’s Kradle”) }
};
books.Update(query, update);
}

//Delete
private void button6_Click(object sender, EventArgs e)
{
var query = new QueryDocument{
{ “author”, “Bad Hemingway” }
};

books.Remove(query);
}
}

}

ok so now where do i use this in real life !!!

Installation of Mongodb

Downloaded the software from the site for my win 7 64 bit machine and unzipped it.

Started the server

as

D:\TechExp\Software\mongodb-win32-x86_64-2.2.2\mongodb-win32-x86_64-2.2.2\bin>mongod –dbpath D:\TechExp\MongoDB

only to get an exception

D:\TechExp\Software\mongodb-win32-x86_64-2.2.2\mongodb-win32-x86_64-2.2.2\bin>mo
ngod
mongod –help for help and startup options
Sun Jan 20 14:44:07 [initandlisten] MongoDB starting : pid=8320 port=27017 dbpat
h=\data\db\ 64-bit host=Badri
Sun Jan 20 14:44:07 [initandlisten] db version v2.2.2, pdfile version 4.5
Sun Jan 20 14:44:07 [initandlisten] git version: d1b43b61a5308c4ad0679d34b262c5a
f9d664267
Sun Jan 20 14:44:07 [initandlisten] build info: windows sys.getwindowsversion(ma
jor=6, minor=1, build=7601, platform=2, service_pack=’Service Pack 1′) BOOST_LIB
_VERSION=1_49
Sun Jan 20 14:44:07 [initandlisten] options: {}
Sun Jan 20 14:44:07 [initandlisten] exception in initAndListen: 10296
*********************************************************************
ERROR: dbpath (\data\db\) does not exist.
Create this directory or give existing directory in –dbpath.
See http://dochub.mongodb.org/core/startingandstoppingmongo
*********************************************************************
, terminating
Sun Jan 20 14:44:07 dbexit:
Sun Jan 20 14:44:07 [initandlisten] shutdown: going to close listening sockets..
.
Sun Jan 20 14:44:07 [initandlisten] shutdown: going to flush diaglog…
Sun Jan 20 14:44:07 [initandlisten] shutdown: going to close sockets…
Sun Jan 20 14:44:07 [initandlisten] shutdown: waiting for fs preallocator…
Sun Jan 20 14:44:07 [initandlisten] shutdown: lock for final commit…
Sun Jan 20 14:44:07 [initandlisten] shutdown: final commit…
Sun Jan 20 14:44:07 [initandlisten] shutdown: closing all files…
Sun Jan 20 14:44:07 [initandlisten] closeAllFiles() finished
Sun Jan 20 14:44:07 dbexit: really exiting now

After looking at the error realized that MongoDB needs a dbpath so created that and restarted the server

D:\TechExp\Software\mongodb-win32-x86_64-2.2.2\mongodb-win32-x86_64-2.2.2\bin>mo
ngod –dbpath D:\TechExp\MongoDB

and and voila the server was running !!!

Sun Jan 20 14:48:46 [initandlisten] MongoDB starting : pid=9228 port=27017 dbpat
h=D:\TechExp\MongoDB 64-bit host=Badri
Sun Jan 20 14:48:46 [initandlisten] db version v2.2.2, pdfile version 4.5
Sun Jan 20 14:48:46 [initandlisten] git version: d1b43b61a5308c4ad0679d34b262c5a
f9d664267
Sun Jan 20 14:48:46 [initandlisten] build info: windows sys.getwindowsversion(ma
jor=6, minor=1, build=7601, platform=2, service_pack=’Service Pack 1′) BOOST_LIB
_VERSION=1_49
Sun Jan 20 14:48:46 [initandlisten] options: { dbpath: “D:\TechExp\MongoDB” }
Sun Jan 20 14:48:46 [initandlisten] journal dir=D:/TechExp/MongoDB/journal
Sun Jan 20 14:48:46 [initandlisten] recover : no journal files present, no recov
ery needed
Sun Jan 20 14:48:46 [initandlisten] waiting for connections on port 27017
Sun Jan 20 14:48:46 [websvr] admin web console waiting for connections on port 2
8017

Now what !!!

 

 

NoSQL & MongoDB…is there something for me in it???

On Friday someone casually asked me if i had ever experienced the joy of working with NoSQL database and i responded i had only heard of it but never used it. Ofcourse being someone that loves technology esp. new ones i decided to read more about it on a cold Saturday morning and it has really excited me. Now this comes from someone that loves RDBMS esp SQL Server however the potential that NoSQL offers and the companies that use it i decided to find out the best one so i could experiment a bit. It seems MongoDB is one such NoSQL database which seemed very popular esp. with some large implementations and best of all free. Who doesnt like free stuff?? Reading through use cases etc it just inspired a 100 ideas just as the flowers bloom in spring…but here we are just in winter so lets see what spring has in store for MongoDB and me…