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.
- [Test]
- public void AddElements()
- {
- var people = new BsonDocument
- {
- {"age", new BsonInt32(27)},
- };
- people.Add("Name", new BsonString("sagar"));
- Console.WriteLine(people);
- }
Output:
We can also rely on implicit conversions of many .Net value types. Let's add an element issued and pass the .Net Boolean value.
- [Test]
- public void AddElements()
- {
- var people = new BsonDocument
- {
- {"age", new BsonInt32(27)},
- {"Isgud", true}
- };
- people.Add("Name", new BsonString("sagar"));
- Console.WriteLine(people);
- }
Output:Let's separate the elements by changing it to JSON method serializes.
- [Test]
- public void SampleEmptyDocument()
- {
- var document = new BsonDocument();
- Console.WriteLine(document);
- }
Output:
Now let's see how to add arrays to a document using a BSON array.
- public void Arrays()
- {
-
- var people = new BsonDocument();
- people.Add("address", new BsonArray(new[] { "533 so and so Plot ", "Flat 101" }));
- Console.WriteLine(people);
- }
Output:Now let's embed the document inside the document as in the following:
- public void EmbedDocument()
- {
- var people = new BsonDocument
- {
- {
-
- "Telecon", new BsonDocument
- {
-
- {"Phone", "9848012345"},
- {"Email", "samplemail.com"}
- }
- }
-
-
- };
- Console.WriteLine(people);
- }
Output:
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.