Introduction

In this article, we will do BSON value operations with BSON documents. Please check the previous articles on MongoDB by visiting the following link:

Let's do some operations to get information from a BSON Document.

Create a new Test called BsonValueOperations as in the following:
  1. [Test]
  2. public void BsonValueOperations()
  3. {
  4. var people = new BsonDocument()
  5. {
  6. {"age","27"}
  7. };
  8. Console.WriteLine(people["age"]);
  9. }
Run the test as in the following:

Bson Value Operation

We get the value 27 as expected. Now let's determine the age after 20 years.

We can apply the "+" operator to add a BSON value and an int using the AsInt32 property to a BSON value to cast to an integer.
  1. [Test]
  2. public void BsonValueOperations()
  3. {
  4. var people = new BsonDocument()
  5. {
  6. {"age", 27}
  7. };
  8. Console.WriteLine(people["age"].AsInt32 +20);
  9. }
embedDocument

We can also check the value of a specific type by using the BSON value is operations.
  1. [Test]
  2. public void BsonValueOperations()
  3. {
  4. var people = new BsonDocument()
  5. {
  6. {"age", 27}
  7. };
  8. Console.WriteLine(people["age"].AsInt32 +20);
  9. Console.WriteLine(people["age"].IsInt32);
  10. Console.WriteLine(people["age"].IsString);
  11. }
BSON value Operation

Now let's serialize the BSON document to BSON.

Create a test as shown below.

We used the Bitconverter.tostring method to show the result in bytes in readable hexadecimal representation.
  1. [Test]
  2. public void ToBson()
  3. {
  4. var people = new BsonDocument()
  5. {
  6. {"Name","sagar"}
  7. };
  8. var bson = people.ToBson();
  9. Console.WriteLine(BitConverter.ToString(bson));
  10. }


Now let us deserialize back into a BSON document representation.
  1. var deserialize = BsonSerializer.Deserialize<BsonDocument>(bson);
  2. Console.WriteLine(deserialize);
This is how the driver communicates with the server.

Summary

In this article, we saw several BSON value operations.