I am working with the MongoDB C# driver. I have a BsonDocument
with some data which includes some MongoDB-specific types (like ObjectIDs and ISODates). I want to convert this to a valid general-purpose JSON string. In other words, I can't have something like _id: ObjectId(...)
or date: ISODate(...)
but would prefer _id: "..."
and date: "..."
. Basically, I want to convert these special types that only MongoDB recognizes to regular strings so they can be parsed more easily. The problem is that a built-in function like .ToJson()
(which another StackOverflow answer suggests) doesn't really convert the document to valid JSON at all because it maintains these special types. My document also contains many levels of arrays and sub-documents, so a simple for loop will not suffice. What's the best way to convert a BsonDocument
that avoids this problem? I would prefer something built-in rather than manually recursing through the document to fix all the issues.
You can convert BsonDocument into a JSON formatted string using MongoDB. Bson. BsonExtensionMethods. ToJson .
Synopsis. The bsondump converts BSON files into human-readable formats, including JSON.
MongoDB stores data in BSON format both internally, and over the network, but that doesn't mean you can't think of MongoDB as a JSON database. Anything you can represent in JSON can be natively stored in MongoDB, and retrieved just as easily in JSON.
JSON is a data format that represents the values of objects, arrays, numbers, strings, booleans, and nulls. The Extended JSON format defines a reserved set of keys prefixed with " $ " to represent field type information that directly corresponds to each type in BSON, the format that MongoDB uses to store data.
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);
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