2011-06-07 59 views
14

如何使用C#驅動程序將BsonArray添加到MongoDB中的BsonDocument?我想結果是這樣的在MongoDB中添加BSON數組到BsonDocument

{ 
    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' } 
    ] 
} 
+0

你能否澄清一下你的問題。你想做什麼?創建上述文件thorugh BsonDocument?或者您試圖向現有作者添加評論? Mb你的節目代碼.. – 2011-06-07 06:28:38

回答

15

您可以用下面的語句創建C#中的上述文件:

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" } } 
    }} 
}; 

您可以測試你是否有與寫結果:

var json = document.ToJson(); 
+0

我還會補充說默認情況下會忽略任何空值。 – 2011-06-08 04:08:18

3

您還可以在BsonDocument已經存在之後添加陣列,如下所示:

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); 
+0

幫助如何創建一個bson數組而不需要在裏面創建一個bsondocument。 – 2014-01-30 12:40:55