![](/img/trans.png)
[英]C# Mongodb merge List<BsonDocument> into single BsonArray
[英]Cannot convert BsonArray to BsonDocument in c#
我有我的Json字符串作为
string myjson = "[
{
"col1": "1",
"col2": "2",
"col3": "3"
},
{
"col1": "4",
"col2": "5",
"col3": "6"
},
{
"col1": "7",
"col2": "8",
"col3": "9"
}]";
问题是:当我创建bson文档时,它正在显示
无法将BsonArray转换为BsonDocument
这就是我创建BsonDocument的方式:
BsonDocument doc = BsonSerializer.Deserialize<BsonDocument>(myjson);
我该怎么办?
BsonDocument doc = new BsonDocument();
BsonArray array = BsonSerializer.Deserialize<BsonArray>(myjson);
doc.Add(array);
我没有尝试过,但是应该可以。
编辑:
string myjson1 = "{ 'col1': '1', 'col2': '2', 'col3': '3'}";
string myjson2 = "{ 'col1': '4', 'col2': '5', 'col3': '6'}";
string myjson3 = "{'col1': '7', 'col2': '8', 'col3': '9'}";
BsonArray arr = new BsonArray();
arr.Add(BsonSerializer.Deserialize<BsonDocument>(myjson1));
arr.Add(BsonSerializer.Deserialize<BsonDocument>(myjson2));
arr.Add(BsonSerializer.Deserialize<BsonDocument>(myjson3));
或仅在文档内部包含一个values
元素,如下所示:
string myjson = "[ { 'col1': '1', 'col2': '2', 'col3': '3'},{ 'col1': '4', 'col2': '5', 'col3': '6'},{'col1': '7', 'col2': '8', 'col3': '9'}]";
var doc = new BsonDocument {
{ "values", BsonSerializer.Deserialize<BsonArray>(myjson) }
};
我能做的最好的就是这个。
您可以尝试将BsonArray转换为BsonValue数组,然后遍历该数组:
var a = BsonSerializer.Deserialize<BsonArray>(yourjsontext).ToArray();
for (int i = 0; i < a.Length; i++) {
var document = a[i].ToBsonDocument();
// Do whatever necessary
}
或更干净的方法:
var arrayDocs = BsonSerializer.Deserialize<BsonArray>(myJsonArrayString);
var documents = arrayDocs.Select(val => val.AsBsonDocument);
这将为您提供IEnumerable<BsonDocument>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.