Simple-MongoDB – Part 1, Getting started

So, I thought it was time for me to write a “Getting started with MongoDB” article but instead of using Sam Corder’s driver, I will use my own: “Simple-MongoDB”. It will be a series of posts covering this topic. This post is the first and will cover how-to get connected and how-to add some entities.

Requirements

  • You have MongoDb up and running. If not, just go to “http://www.mongodb.org” and download the server part and start it. You can also read the first part of my earlier writings: Getting started with MongoDB – Using Json.Net and Castle Dynamic proxy
  • Visual Studio 2010 – I have built the driver using VS2010 and have targeted the 4.0-framework. I guess there would be quite easy to port it to a former version.

Step 1 – Download Simple-MongoDB

Head over to the project site: http://code.google.com/p/simple-mongodb and download the code. There’s two Zip-files:

  • Pls-SimpleMongoDb – v[X]-Bin.zip: Contains the release-compiled dll
  • Pls-SimpleMongoDb – v[X]-Source.zip: Contains the Visual Studio 2010 Solution

The latest code is of course available via the Trunk.

Step 2 – Create a new project

Create a new project and add a reference to the Pls.SimpleMongoDB.dll (if you test with an Console-application, ensure that to switch to Full .Net 4.0 framework and not just Client profile).

Step 3 – Get connected with the MongoDB server

This article shows how to consume the App.config and shows how to manually use the sessionfactory, which is something you probably would let your IoC handle for you.

App.config – Connectionstring

<connectionStrings>
  <add name="Pls.Simo.GettingStarted" connectionString="host:localhost;port:27017"/>
</connectionStrings>

Establish a connected Session

var sessionFactory = new SimoSessionFactory();
using (var session = sessionFactory.GetSession("Pls.Simo.GettingStarted"))
{
    //...
}

If you want to go with the default values from MongoDB {host : localhost, port : 27017 }; you can just use the sessionFactory.GetSession() – overload instead:

using (var session = sessionFactory.GetSession())
{
    //...
}

Step 4 – Add some data

Simple-MongoDB is designed to work with typed-classes, anonymous types as well as JSON-strings. We will start by looking at the typed-classes scenario. The simplest way to store entities is by consuming the EntityStore-API. It lies on-top of the Session-API and is designed to work with entities. The type-name of an entity is implicitly used as the collectionname and by default, consumes Microsofts Pluralizer to pluralize namings. This can of course be turned of (entityStore.Session.Pluralizer.Disable();).

Using the EntityStore-API

var sessionFactory = new SimoSessionFactory();
using (var session = sessionFactory.GetSession("Pls.Simo.GettingStarted"))
{
    var entityStore = new SimoEntityStore(session, "MyDatabase");

    var interestingUrl = new InterestingUrl(@"http://daniel.wertheim.se") { Description = "Some good writings about the Simple-MongoDB driver." };
    interestingUrl.SetTags("Simple-MongoDB", "Blog");
    entityStore.Insert(interestingUrl);
}

You can of course consume the Session-API, if you want. It also contains some methods that the EntityStore doesn’t. The Session-API lets you get references to databases and collections, and the work with them in a way that mimics MongoDB.

Using the Session-API

var sessionFactory = new SimoSessionFactory();
using (var session = sessionFactory.GetSession("Pls.Simo.GettingStarted"))
{
    var db = session["MyDatabase"];
    var collection = db.GetCollection<InterestingUrl>();

    var interestingUrl = new InterestingUrl(@"http://code.google.com/p/simple-mongodb") { Description = "The home of the Simple-MongoDB driver." };
    interestingUrl.SetTags("Simple-MongoDB", "Project site");
    collection.Insert(interestingUrl);
}

You can of course get a reference to the collection by specifying a string. But remember to take control of the pluralization.

var collection = session["MyDatabase"]["InterestingUrls"];

Step 5 – Querying

You can query by sending: either a JSON-string, anonymous-typ, typed C# class; as the selector to the Find-methods. There is a Fluent querying API that lets you help with the generation of JSON-query strings. To get more info on querying, look here: http://www.mongodb.org/display/DOCS/Advanced+Queries

Using anonymous type

var sessionFactory = new SimoSessionFactory();
using (var session = sessionFactory.GetSession("Pls.Simo.GettingStarted"))
{
    var entityStore = new SimoEntityStore(session, "MyDatabase");

    var interestingUrl = entityStore.FindOne<InterestingUrl>(new { Url = @"http://daniel.wertheim.se" });
}

Using Query-expression
The query-expression operates on the fluent Query-API and translates the query to JSON, which is then passed to the selector.

var sessionFactory = new SimoSessionFactory();
using (var session = sessionFactory.GetSession("Pls.Simo.GettingStarted"))
{
    var entityStore = new SimoEntityStore(session, "MyDatabase");

    var interestingUrl = entityStore.FindOne<InterestingUrl>(
        q => q["Url"].IsEq(@"http://code.google.com/p/simple-mongodb").And("Tags").HasAll("Simple-MongoDB", "Project site"));
}

That’s it for now. The next post will be posted shortly and will deal with Querying.

Download sample with code from this article.

//Daniel

Advertisement
Tagged ,

5 thoughts on “Simple-MongoDB – Part 1, Getting started

  1. Simple-MongoDB – Part 1, Getting started « Daniel Wertheim…

    Thank you for submitting this cool story – Trackback from DotNetShoutout…

  2. [...] Simple-MongoDB – Part 1, Getting started – Daniel Wertheim begins an introductory series of posts looking a the MongoDB NoSQL database solution, also exploring his simple MongoDB driver [...]

  3. [...] This post was mentioned on Twitter by Elijah Manor, dgmike and topsy_top20k, Daniel Wertheim. Daniel Wertheim said: Simple-MongoDB – Part 1, Getting started – http://bit.ly/a1x25R #MongoDB [...]

  4. [...] Simple-MongoDB – Part 1 and Part2 For .net / C# devs [...]

Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.