Convert MongoDB BsonDocument to valid JSON in C#

MongoDB.Bson (2.5+) has support to map between BsonValues and .Net objects.
BsonTypeMapper Class

To map a BsonValue (or BsonDocument) to .Net object use

var dotNetObj = BsonTypeMapper.MapToDotNetValue(bsonDoc);

You can then use your choice of serialization library. For example,

JsonConvert.SerializeObject(dotNetObj);

If you have a List of BsonDocument

var dotNetObjList = bsonDocList.ConvertAll(BsonTypeMapper.MapToDotNetValue);

Leave a Comment

tech