Adding BSON array to BsonDocument in MongoDB

Ravi picture Ravi · Jun 7, 2011 · Viewed 28.9k times · Source

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' }
    ]
} 

Answer

Robert Stam picture Robert Stam · Jun 8, 2011

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();