string data = "[ 1, 2, 3 ]"; // BSON array data byte[] bsonData = BsonSerializer.Deserialize(data).ToBson(); // convert to BSON byte array MemoryStream stream = new MemoryStream(bsonData); // create memory stream BsonReader reader = new BsonReader(stream); // create BsonReader object reader.ReadStartArray(); // read start of array while(reader.ReadBsonType() != BsonType.EndOfDocument) // loop through array elements { Console.WriteLine(reader.ReadDouble()); // print array element value } reader.ReadEndArray(); // read end of array
var bson = new BsonDocument { { "name", "John" }, { "age", 30 }, { "friends", new BsonArray { "Mary", "Tom", "Sara" } } }; MemoryStream stream = new MemoryStream(); BsonSerializer.Serialize(stream, bson); // serialize BSON data to stream BsonReader reader = new BsonReader(stream); // create BsonReader object reader.ReadStartDocument(); // read start of document while(reader.ReadBsonType() != BsonType.EndOfDocument) // loop through document elements { if(reader.CurrentBsonType == BsonType.Array) // check if element is an array { reader.ReadStartArray(); // read start of array while(reader.ReadBsonType() != BsonType.EndOfDocument) // loop through array elements { Console.WriteLine(reader.ReadString()); // print array element value } reader.ReadEndArray(); // read end of array } else // element is not an array { reader.Read(); // read element } } reader.ReadEndDocument(); // read end of documentThis example creates a BsonDocument object with three elements: a string, an integer, and an array. The BsonDocument is serialized to a MemoryStream using the BsonSerializer class. A BsonReader object is then created using the stream, and the ReadStartDocument method is called to read the start of the document. A while loop is used to loop through all the elements in the document. If an element is an array, the ReadStartArray method is called to read the start of the array and another while loop is used to loop through all the array elements. The element value is printed to the console using the ReadString method. Finally, the ReadEndArray method is called to read the end of the array and the Read method is called to read all other element types. The ReadEndDocument method is called to read the end of the document. Package library: MongoDB.Driver.Core.