Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding BSON array to BsonDocument in MongoDB

Tags:

How can I add BsonArray to BsonDocument in MongoDB using a C# driver? I want a result something like this

{      author: 'joe',     title : 'Yet another blog post',     text : 'Here is the text...',     tags : [ 'example', 'joe' ],     comments : [ { author: 'jim', comment: 'I disagree' },                  { author: 'nancy', comment: 'Good post' }     ] }  
like image 482
Ravi Avatar asked Jun 07 '11 05:06

Ravi


People also ask

What is BSON array?

A BSON binary binData value is a byte array. A binData value has a subtype that indicates how to interpret the binary data.

Why does MongoDB use BSON rather than JSON?

BSON's binary structure encodes type and length information, which allows it to be traversed much more quickly compared to JSON. BSON adds some non-JSON-native data types, like dates and binary data, without which MongoDB would have been missing some valuable support.

What is BsonDocument in MongoDB?

BsonDocument is the default type used for documents. It handles dynamic documents of any complexity. For instance, the document { a: 1, b: [{ c: 1 }] } can be built as follows: var doc = new BsonDocument { { "a", 1 }, { "b", new BsonArray { new BsonDocument("c", 1) }} };


1 Answers

You can create the above document in C# with the following statement:

var document = new BsonDocument {     { "author", "joe" },     { "title", "yet another blog post" },     { "text", "here is the text..." },     { "tags", new BsonArray { "example", "joe" } },     { "comments", new BsonArray {         new BsonDocument { { "author", "jim" }, { "comment", "I disagree" } },         new BsonDocument { { "author", "nancy" }, { "comment", "Good post" } }     }} }; 

You can test whether you produced the correct result with:

var json = document.ToJson(); 
like image 172
Robert Stam Avatar answered Sep 19 '22 18:09

Robert Stam