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
By developing with C# and MongoDB together one opens up a world of possibilities. Console, window, and web applications are all possible. As are cross-platform mobile applications using the Xamarin framework.
Now that libbson is compiled, let's install it using msbuild. It will be installed to the path specified by CMAKE_INSTALL_PREFIX . Now let's do the same for the MongoDB C driver. All of the MongoDB C Driver's components will now be found in C:\mongo-c-driver .
Driver Core is a full driver with complete support for all types of deployment configurations, authentication, SSL, and cursors. The API is verbose, but highly configurable which is why it's a great solution to build higher-level APIs upon. The [MongoDB .
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)
Currently, there is no support for dynamic in the MongoDB driver. This is because it is based on .NET 3.5. However, since a .NET 4.0 assembly can reference a .NET 3.5 assembly, it is possible for you to write a IBsonSerializationProvider and an IBsonSerializer in .NET 4.0 to support dynamics.
We, 10gen, are looking at doing this in the future. I have spiked some support at https://github.com/craiggwilson/mongo-csharp-driver/tree/dynamic if you want to take a look. There are most definitely bugs, but it shows that it is possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With