Is there mongodb C# driver support System.Dynamic.DynamicObject in .NET 4?

hoang picture hoang · Apr 19, 2012 · Viewed 14k times · Source

Im working on a project that use .NET Razor and mongodb. I would like to do something like this:

@{
    var feeds = DP.Database.GetCollection("feeds").FindAll();
}
<ul>
    @foreach (dynamic feed in feeds)
    {
        <li>@feed.message - @feed.from.name</li>
    }
</ul>

However, the current mongodb C# driver FindAll() return collection of BsonDocument which does not support dynamic object. Anybody know a .NET 4 dynamic supported mongodb C# driver?

Thanks a lot

Answer

Maximilian Scherer picture Maximilian Scherer · Oct 25, 2012

I created a straight-forward extension to the MongoDB driver that re-serializes the BSON document using Json.NET and deserializes it as a dynamic. By including the following class, you can simply convert your MongoDB queries to dynamic like this

dynamic obj = collection.FindOneByIdAs<BsonDocument>(someObjectId).ToDynamic();

Extension class:

public static class MongoDynamic
{
    private static System.Text.RegularExpressions.Regex objectIdReplace = new System.Text.RegularExpressions.Regex(@"ObjectId\((.[a-f0-9]{24}.)\)", System.Text.RegularExpressions.RegexOptions.Compiled);
    /// <summary>
    /// deserializes this bson doc to a .net dynamic object
    /// </summary>
    /// <param name="bson">bson doc to convert to dynamic</param>
    public static dynamic ToDynamic(this BsonDocument bson)
    {
        var json = objectIdReplace.Replace(bson.ToJson(), (s) => s.Groups[1].Value);
        return Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(json);
    }
}

Be sure to reference Newtonsoft.Json.dll (http://james.newtonking.com/projects/json-net.aspx)