I’m using the C# Driver, at this point I’m using the ToJson method to convert the BsonDocument to text for output.
I like to use the built-in formatted output, so I tried using JsonWriterSettings and setting Indent=true:
var settings = new JsonWriterSettings(){ Indent = true } BsonDocument.ToJson(settings)
At present, the output result is still not completely formatted, only the outermost layer has indentation processing, and the data of array type is still not formatted for output. So I want to understand how to do full Json formatting using built-in functions.
I tried to reproduce the behaviour with the following example:
using MongoDB.Bson;
using MongoDB.Bson.IO;
var bsonDocument = BsonDocument.Parse("{name: 'Alice', favouriteNumbers: [7,42,99], favouriteFruit: ['apple','orange','grapefruit','watermelon'], favouriteBook: { name: 'Stranger in a Strange Land', author: 'Robert A. Heinlein'}}");
var settings = new JsonWriterSettings { Indent = true };
var jsonOutput = bsonDocument.ToJson(settings);
Console.WriteLine(jsonOutput);
We observe that field names are quoted, arrays are formatted, and elements are indented correctly based on their nesting. Please provide a code example that does not produce the desired output so that we can better understand the problem.
The JsonWriter included in MongoDB.Bson does not indent arrays, only subdocuments. You would have to write your own CustomJsonWriter. Alternatively you could use the technique that I outlined and post-process the output to add new lines and indentation to array elements.