【发布时间】:2016-03-08 18:03:59
【问题描述】:
我正在使用MongoDB.Net driver 解析存储<Country> 类型列表(包含name 和code)的Json 文档。但我不确定如何从 Bson 文档中检索该国家/地区列表。
我逐步完成了解析代码,所有值都被解析到 CountryModel 中。然后存储在返回的collection var 中。
谷歌搜索给我带来了this solution,但它只显示了如何按 ID 返回记录而不是完整列表。我想知道是否可以在这里使用 Lambda 重载来查找列表。
到目前为止,我已经设法检索到完整的文档,并将其分配给一个列表:
countries = collection.Find(new BsonDocument()).ToListAsync().GetAwaiter().GetResult();
有谁知道我如何只获取List<Country> 而不是整个文档?
检索数据涉及的两种主要方法如下:
public void LoadDb()
{
var collection = StartConnection();
countries = collection.Find(new BsonDocument()).ToListAsync().GetAwaiter().GetResult();
}
public IMongoCollection<CountryModel> StartConnection()
{
var client = new MongoClient(connectionString);
var database = client.GetDatabase("orders");
//Get a handle on the countries collection:
var collection = database.GetCollection<CountryModel>("countries");
return collection;
}
这是解析的 Json 数据示例:
{
"_id": {
"$oid": "565f5d3ae4b0ed465284d17a"
},
"countries": [
{
"name": "Afghanistan",
"code": "AF"
},
{
"name": "Antigua and Barbuda",
"code": "AG"
}
]
}
这是支持 POCO 类,CountryModel:
namespace MongoDBApp.Models
{
[ImplementPropertyChanged]
public class CountryModel
{
[BsonId]
public ObjectId Id { get; set; }
[BsonElement("countries")]
public List<Country> countries { get; set; }
}
[ImplementPropertyChanged]
public class Country
{
[BsonElement("name")]
public string Name { get; set; }
[BsonElement("code")]
public string Code { get; set; }
}
}
【问题讨论】:
-
您是否希望在一个数组中返回所有文档中的国家子文档?
-
我希望将国家/地区子文档中的所有国家/地区作为列表或数组返回。
标签: c# json list mongodb-.net-driver bson