受欢迎的博客标签

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

Published

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.Serializationnamespace.

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;}

}.