How to convert a BsonDocument into a strongly typed object with the official MongoDB C# driver?

The MongoDB Driver does provide a method for deserializing from Bson to your type. The BsonSerializer can be found in MongoDB.Bson.dll, in the MongoDB.Bson.Serialization namespace.

You can use the BsonSerializer.Deserialize<T>() method. Some example code would be

var obj = new MyClass { MyVersion = new Version(1,0,0,0) };
var bsonObject = obj.ToBsonDocument();
var myObj = BsonSerializer.Deserialize<MyClass>(bsonObject);
Console.WriteLine(myObj);

Where MyClass is defined as

public class MyClass
{
    public Version MyVersion {get; set;}
}

I hope this helps.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)