Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert MongoDB BsonDocument to valid JSON in C#

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.

like image 634
CynicalProgrammer Avatar asked Nov 25 '14 17:11

CynicalProgrammer


People also ask

How do you convert BsonDocument to string?

You can convert BsonDocument into a JSON formatted string using MongoDB. Bson. BsonExtensionMethods. ToJson .

Can you convert BSON to JSON?

Synopsis. The bsondump converts BSON files into human-readable formats, including JSON.

Is MongoDB document same as 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.

What is JSON format in MongoDB?

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.


Video Answer


1 Answers

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); 
like image 192
sandiejat Avatar answered Nov 11 '22 15:11

sandiejat