Skip to content

Instantly share code, notes, and snippets.

@vquaiato
Created May 15, 2015 22:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vquaiato/6406c5486361cc674753 to your computer and use it in GitHub Desktop.
Save vquaiato/6406c5486361cc674753 to your computer and use it in GitHub Desktop.
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);
}
/// <summary>
/// deserializes this BsonDocument cursor result to a list of .net dynamic objects
/// </summary>
/// <param name="cursor">cursor result to convert to dynamic</param>
/// <returns></returns>
public static List<dynamic> ToDynamicList(this MongoCursor<BsonDocument> cursor)
{
var dynamicList = new List<dynamic>();
var list = cursor.ToList();
for (int i = 0, l = list.Count; i < l; i++)
dynamicList.Add(list[i].ToDynamic());
return dynamicList;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment