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:
- [Test]
- public void BsonValueOperations()
- {
-
- var people = new BsonDocument()
- {
- {"age","27"}
-
- };
- Console.WriteLine(people["age"]);
-
- }
Run the test as in the following:
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);
This is how the driver communicates with the server.
SummaryIn this article, we saw several BSON value operations.