如何从Bson文档中获取值列表
本文关键字:获取 列表 文档 Bson | 更新日期: 2023-09-27 18:25:31
我正在使用MongoDB.Net驱动程序解析Json文档,该文档存储类型为<Country>
(包含name
和code
)的列表。但我不知道如何从Bson文件中检索国家列表。
我逐步完成了解析代码,所有值都被解析到CountryModel中。然后存储在返回的collection
变量中
谷歌给我带来了这个解决方案,但它只显示如何按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; }
}
}
尝试投影:
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
:中使用Id为的Find
collection.Find(x => x.Id == "sample_object_id")