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:
Create a new Test called BsonValueOperations as in the following:
- [Test]
- public void BsonValueOperations()
- {
- var people = new BsonDocument()
- {
- {"age","27"}
- };
- Console.WriteLine(people["age"]);
- }

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.
- [Test]
- public void BsonValueOperations()
- {
- var people = new BsonDocument()
- {
- {"age", 27}
- };
- Console.WriteLine(people["age"].AsInt32 +20);
- }

We can also check the value of a specific type by using the BSON value is operations.
- [Test]
- public void BsonValueOperations()
- {
- var people = new BsonDocument()
- {
- {"age", 27}
- };
- Console.WriteLine(people["age"].AsInt32 +20);
- Console.WriteLine(people["age"].IsInt32);
- Console.WriteLine(people["age"].IsString);
- }

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.
- [Test]
- public void ToBson()
- {
- var people = new BsonDocument()
- {
- {"Name","sagar"}
- };
- var bson = people.ToBson();
- Console.WriteLine(BitConverter.ToString(bson));
- }

Now let us deserialize back into a BSON document representation.
- var deserialize = BsonSerializer.Deserialize<BsonDocument>(bson);
- Console.WriteLine(deserialize);

Summary
In this article, we saw several BSON value operations.

Join the conversation! Your thoughts help the community grow.