Подтвердить что ты не робот

Добавление массива BSON в BsonDocument в MongoDB

Как добавить BsonArray в BsonDocument в MongoDB с помощью драйвера С#? Я хочу получить что-то вроде этого

{ 
    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' }
    ]
} 
4b9b3361

Ответ 1

Вы можете создать вышеуказанный документ в С# со следующим утверждением:

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

Ответ 2

вы также можете добавить массив после того, как 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);