24

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' }
    ]
} 
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ravi
  • 2,470
  • 3
  • 26
  • 32
  • Can you please clarify you question. What are you trying to do? Create above described document thorugh BsonDocument? Or you trying to add comment to existing author? Mb your show code.. – Andrew Orsich Jun 07 '11 at 06:28

2 Answers2

32

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();
derekbaker783
  • 8,109
  • 4
  • 36
  • 50
Robert Stam
  • 12,039
  • 2
  • 39
  • 36
11

you can also add the array after the BsonDocument already exists, like this:

BsonDocument  doc = new BsonDocument {
    { "author", "joe" },
        { "title", "yet another blog post" },
     { "text", "here is the text..." }
};

BsonArray  array1 = new BsonArray {
        "example", "joe"
    };


BsonArray  array2 = new BsonArray {
        new BsonDocument { { "author", "jim" }, { "comment", "I disagree" } },
        new BsonDocument { { "author", "nancy" }, { "comment", "Good post" } }
    };


doc.Add("tags", array1);
doc.Add("comments", array2);
Inbal Abraham
  • 111
  • 1
  • 2