Using Mongo DB BSON Value Operations

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.     
  5.     var people = new BsonDocument()
  6.     {
  7.         {"age","27"}
  8.     
  9.     };      
  10.     Console.WriteLine(people["age"]);
  11.     
  12. }
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.    
  3.  public void BsonValueOperations()   
  4.  {   
  5.        var people = new BsonDocument()   
  6.        {   
  7.              {"age", 27}   
  8.        };   
  9.        Console.WriteLine(people["age"].AsInt32 +20);   
  10.  }   
embedDocument

We can also check the value of a specific type by using the BSON value is operations.
  1. [Test]   
  2.    
  3.  public void BsonValueOperations()   
  4.  {   
  5.    
  6.     var people = new BsonDocument()   
  7.     {   
  8.           {"age", 27}   
  9.     };   
  10.    Console.WriteLine(people["age"].AsInt32 +20);   
  11.    Console.WriteLine(people["age"].IsInt32);   
  12.    Console.WriteLine(people["age"].IsString);   
  13. }
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.    
  5.        var people = new BsonDocument()   
  6.        {   
  7.              {"Name","sagar"}   
  8.    
  9.        };   
  10.    
  11.        var bson = people.ToBson();   
  12.        Console.WriteLine(BitConverter.ToString(bson));   
  13.    
  14.  }   


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.


Similar Articles