将BSON数组添加到MongoDB中的BsonDocument中

本文关键字:中的 BsonDocument MongoDB BSON 数组 添加 | 更新日期: 2023-09-27 17:58:37

如何使用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' }
    ]
} 

将BSON数组添加到MongoDB中的BsonDocument中

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