Reading

The IBsonReader interface contains all the methods necessary to read a BSON document or a JSON document. There is an implementation for each format.

BSON

BsonBinaryReader is for reading binary BSON. For example, to read a BSON file containing the document { a: 1 }:

string inputFileName; // initialize to a file containing BSON

using (var stream = File.OpenRead(inputFileName))
using (var reader = new BsonBinaryReader(stream))
{
    reader.ReadStartDocument();
    string fieldName = reader.ReadName();
    int value = reader.ReadInt32();
    reader.ReadEndDocument();
}

JSON

In the same way, we can read a JSON string using a JsonReader. For example, to read the document { a: 1 }:

var jsonString = "{ a: 1 }";
using (var reader = new JsonReader(jsonString))
{
    reader.ReadStartDocument();
    string fieldName = reader.ReadName();
    int value = reader.ReadInt32();
    reader.ReadEndDocument();
}

JsonReader supports reading strict JSON as well as both flavors of MongoDB Extended JSON.

Writing

The IBsonWriter interface contains all the methods necessary to write a BSON document or a JSON document. There is an implementation for each format.

BSON

BsonBinaryWriter is for writing binary BSON. For example, to write the document { a: 1 } to a BSON file:

string outputFileName; // initialize to the file to write to.

using (var stream = File.OpenWrite(outputFileName))
using (var writer = new BsonBinaryWriter(stream))
{
    writer.WriteStartDocument();
    writer.WriteName("a");
    writer.WriteInt32(1);
    writer.WriteEndDocument();
}

JSON

In the same way, we can write a JSON string using a JsonWriter. For example, to write the document { a: 1 }:

string outputFileName; // initialize to the file to write to.

using (var output = new StreamWriter(outputFileName))
using (var writer = new JsonWriter(output))
{
    writer.WriteStartDocument();
    writer.WriteName("a");
    writer.WriteInt32(1);
    writer.WriteEndDocument();
}

Settings

JsonWriter supports writing strict JSON as well as both flavors of MongoDB Extended JSON. This, and other things, can be customized with the JsonWriterSettings class.

For instance, to write in a format for the MongoDB Shell, you can set the OutputMode to Shell and also set the ShellVersion to the desired shell version.

var settings = new JsonWriterSettings
{
    OutputMode = JsonOutputMode.Shell,
    ShellVersion = new Version(3.0) // target the syntax of MongoDB 3.0
};