将BSON数组添加到MongoDB中的BsonDocument

如何使用C#驱动程序将BsonArray添加到MongoDB中的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' } ] } 

您可以使用以下语句在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(); 

你也可以在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);