![](/img/trans.png)
[英]How to get the values from keys in bson document in order to put in a ListBox (C#)
[英]How to fetch a list of values from a Bson document?
我正在使用MongoDB.Net驱动程序在Json文档中解析,该文档存储类型<Country>
(包含name
和code
)的列表 。 但我不确定如何从Bson文档中检索国家列表。
我逐步解析了解析代码,所有值都被解析为CountryModel。 然后存储在返回的collection
var中。
谷歌搜索给我带来了这个解决方案,但它只显示了如何通过ID而不是完整的List返回记录。 我想知道是否可以在这里使用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; }
}
}
尝试投影:
var result = await collection.Find(x => x.Id == {ObjectId}).Project(x => x.countries).FirstOrDefaultAsync();
其中{ObjectId}是您要从中获取国家/地区集合的CountryModel的ID。
顺便说一句:使用ObjectId
有更方便的方法。 您可以在模型中放置string
并添加属性:
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
然后你可以在string
使用Find
with Id:
collection.Find(x => x.Id == "sample_object_id")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.