Although mongodb-csharp diver syntactically allows you to add to document every object (Document’s Append and Add methods have (string, object) signature) you can’t add an arbitrary object just because the driver only supports basic data types (numbers (but not all), strings) and Enumerations. But if you want to do something like this:
House house = new House("Springfield", new Room[]
{
new Room{
Length = 2,
Width = 2
},
new Room{
Length = 3,
Width = 3
}
});
to get something like this
{
"Address": "Springfield",
"Rooms": [
{ "Length": 2, "Width": 2 },
{ "Length": 3, "Width": 3 }
]
}
Well, now we can do it with MongoSerializer.
So what can we do with MongoSerializer?
Just the same things as with XmlSerializer - serialize and deserialize (well, for this time just serialize :-)
However there're some interesting side effects:
Due to the fact that mongo documents actually stored in a MongoCollection we can use all mongo features - indexing, very fast queries, etc.
Basically, with MongoSerializer you can convert regular .NET object to key/value representation:
Document Serialize(Object)
With this basic operation you still have to add documents to MongoCollection manually.
House house = new House("Springfield", new Room[]
{
new Room{
Length = 2,
Width = 2
},
new Room{
Length = 3,
Width = 3
}
});
Console.WriteLine("Now we will convert House instance to Document\r\n");
Document document = house.Serialize();
// let's see the string representation
Console.WriteLine(document.ToString());
Console.WriteLine("Press Enter key\r\n\r\n");
Console.ReadLine();
Console.WriteLine("now we'll convert an atomic value\r\n");
document = 1.Serialize();
// let's see the string representation again!
Console.WriteLine(document.ToString());
Console.WriteLine("Note that atomic object have added to the document with the empty key");
Console.WriteLine("Press Enter key\r\n\r\n");
Console.ReadLine();
Console.WriteLine("ok, how to convert a collection?\r\n");
var rooms = house.Rooms;
document = rooms.Serialize();
Console.WriteLine(document.ToString());
Console.WriteLine("Well again, collection was edded with the empty key");
Console.WriteLine("Press Enter key\r\n\r\n");
Console.ReadLine();
Console.WriteLine("To properly convert an enumeration or a collection you need to convert its members one-by-one on a loop. Or just use anonymous type: new { rooms = rooms }\r\n");
document = new { rooms = rooms }.Serialize();
Console.WriteLine(document.ToString());
Console.WriteLine("The End.");
Console.ReadLine();
MongoSerializer.zip (292.88 kb) [Downloads: 199]
Serializer, Asp.net Membership and Role providers... and may be something more by now