MongoDB and C# Dynamics
I am a big fan of MongoDB.
There is a good C# driver called, MongoDB-CSharp. Unfortunately, because of the strongly typed nature of C#, the default implementation requires you to work with your data as a dictionary. This has an unfortunate side effect of some ugly code and a quite a bit of casting.
Given a choice of working with a dictionary vs SQL I would choice a dictionary everyday. However, with C# 4.0’s dynamics, we can make this much easier to work with.
The change in usage is minor, but I find it to be much more readable and productive.
Before:
1: Mongo mongo = new Mongo();
2: mongo.Connect();
3:
4: var db = mongo["blog"];
5:
6: var posts = db["posts"];
7:
8: Document post = new Document();
9: post["Title"] = "Hello Mongo World";
10: post["Body"] = "This is my first MongoDB post!";
11: post["Published"] = DateTime.UtcNow;
12: post["Tags"] = new[] { "NoSQL", "MongoDB", "greatness" };
13: post["Slug"] = "mongo-post";
14:
15: posts.Insert(post);
16:
17: Document query = new Document();
18: query[“Slug”] = "mongo-post";
19:
20:
21: Document mongo_post = posts.FindOne(query);
22:
23: string title = mongo_post["Title"] as string;
24: DateTime published = ((DateTime)mongo_post["Published"]).ToLocalTime();
25:
26: Console.WriteLine("Title: {0} local published time {1} ", title, published);
After:
1: Mongo mongo = new Mongo();
2: mongo.Connect();
3:
4: var db = mongo["blog"];
5:
6: var posts = db["posts"];
7:
8: dynamic post = new Document();
9: post.Title = "Hello Mongo World";
10: post.Body = "This is my first MongoDB post!";
11: post.Published = DateTime.UtcNow;
12: post.Tags = new[] { "NoSQL", "MongoDB", "greatness" };
13: post.Slug = "mongo-post";
14:
15: posts.Insert(post);
16:
17: dynamic query = new Document();
18: query.Slug = "mongo-post";
19:
20:
21: var mongo_post = posts.FindOne(query);
22:
23: string title = mongo_post.Title;
24: DateTime published = mongo_post.Published.ToLocalTime();
25:
26: Console.WriteLine("Title: {0} local published time {1} ", title, published);
While the example is trivial, I think it is a good step forward.
I want to play around with a bit more before I try to figure out how to submit a patch or fork it.
In the mean time, if you want play with the code, download the source from github, and then swap out the Document.cs class with this file.


