Using Mongo DB Creating Documents With BSON Document Part 2

Introduction

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

Using mongodb with ASP.NETMVC

Now let's add the element using the add method and collection initializer.

Here we added the age element using a collection intializer and created a value of BsonInt32 and pass an age of 27.

  1. [Test]    
  2. public void AddElements()    
  3. {    
  4.     var people = new BsonDocument    
  5.     {    
  6.         {"age"new BsonInt32(27)},    
  7.     };    
  8.     people.Add("Name"new BsonString("sagar"));    
  9.     Console.WriteLine(people);    
  10. }   

 Output:

value of BsonInt32

We can also rely on implicit conversions of many .Net value types. Let's add an element issued and pass the .Net Boolean value.

  1. [Test]    
  2. public void AddElements()    
  3. {    
  4.     var people = new BsonDocument    
  5.     {    
  6.        {"age"new BsonInt32(27)},    
  7.        {"Isgud"true}    
  8.     };    
  9.     people.Add("Name"new BsonString("sagar"));    
  10.     Console.WriteLine(people);    
  11. }   
Output:

add an element issued

Let's separate the elements by changing it to JSON method serializes.
  1. [Test]    
  2. public void SampleEmptyDocument()    
  3. {    
  4.     var document = new BsonDocument();    
  5.     Console.WriteLine(document);    
  6. }    
Output:

JSON method serializes

Now let's see how to add arrays to a document using a BSON array.
  1. public void Arrays()    
  2.     
  3.     var people = new BsonDocument();    
  4.     people.Add("address"new BsonArray(new[] { "533 so and so Plot ""Flat 101" }));    
  5.     Console.WriteLine(people);    
  6. }   
Output:

add arrays to a document

Now let's embed the document inside the document as in the following:
  1. public void EmbedDocument()    
  2. {    
  3.      var people = new BsonDocument    
  4.      {    
  5.          {    
  6.  
  7.             "Telecon"new BsonDocument    
  8.             {    
  9.     
  10.                {"Phone""9848012345"},    
  11.                {"Email""samplemail.com"}    
  12.             }    
  13.          }    
  14.     
  15.     
  16.      };    
  17.              Console.WriteLine(people);    
  18. }    
Output:

document inside the document

Whereas in SQL Server we need an entire separate table to store this information and we need to do it with the foreign keys again.
These are the basics of creating documents with the BSON document model.

Summary

In this article we have learned about BSON documents and creation of documents using the BSON document model. 


Similar Articles