Optimize JSON Output in MongoDB ToJson

This code converts a BsonDocument to JSON using:

BsonDocument bson = new { Name = "someone" }.ToBsonDocument(); 
string json = bson.ToJson(new JsonWriterSettings { OutputMode = JsonOutputMode.RelaxedExtendedJson });


The expected JSON output is {name:"someone"}, but the actual output contains spaces as { name : "someone" }.

I am concerned about the potential impact on bandwidth usage due to these unnecessary spaces in the JSON output. How I can ensure that the output matches the expected format without unnecessary spaces?

Hello @Nima_Niazmand

2 points:

  • If you are concerned about bandwidth, run some tests and determine if your concern is well founded.
  • Have you tried the other JsonMode constants?

Yep, it takes 13 percent more bandwidth. And Yep I tried everything. Also Newton BSON serializer works fine.

1 Like

@Nima_Niazmand if bandwidth is a concern the .NET driver supports network compression which would greatly reduce any overhead introduced by this whitespace.

It’s already GZIP. Without spaces, it’s 13% smaller, give or take. Also, driver compression works between the database and the backend. The problem is in the backend and frontend.
Anyway, I wrote my own BSON stringify. Apparently, the C# driver dev team forgot to apply the open-close principle to the library.