My previous posts on MongoDB have been pretty un-.NETty, in that I have focused almost entirely on how to work the DB through its JavaScript API. To remedy that, I shall write a few short posts on how to get rolling with MongoDB using NoRM, the coolest C# driver for MongoDB at the moment.
First post will be on how to connect and shove data into MongoDB.
Short introduction to NoRM
NoRM is “No Object-Relational Mapping”. It’s a .NET-driver, that allows you to map objects and their fields and aggregated objects into documents. I like NoRM because it’s successfully preserved that low-friction MongoDB-feeling, bridging C#’s capabilities nicely to those of JavaScript in the best possible way, providing some extra C#-goodies along the way. Please read on, you’ll see…
Connect to MongoDB
Easy – can be done like so:
1 2 3 4 |
using(var mongo = Mongo.Create("mongodb://hostname/dbname")) { // go crazy in here!!1 } |
Inserting a few documents
Inserting documents with NoRM is easy – just create a class with fields and aggregated objects, and make sure the class either has a property named something like “Id” or has a property decorated with [MongoIdentifier], e.g. like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public class Order { public Order() { Id = ObjectId.NewObjectID(); Items = new List<Item>(); } public ObjectId Id { get; set; } public int Number { get; set; } public List<Item> Items { get; set; } } public class Item { public string Name { get; set; } public int Amount { get; set; } } |
– and then go ahead and pull a strongly typed collection and insert documents into it:
1 2 3 4 5 6 7 8 9 |
var orders = mongo.GetCollection<Order>(); orders.Insert(new Order { Number = 1, Items = { new Item { Name = "beer" }, new Item { Name = "nuts" }, } }); |
Now, to make this work I need to create five 200-line XML-files with mapping info etc. </kidding> no, seriously – that’s all it takes to persist an entire aggregate root!!
Pretty cool, eh? That’ s what I meant when I said low friction. Stay tuned for more posts, e.g. on how to query a collection…