如何从Bson文档中获取值列表? [英] How to fetch a list of values from a Bson document?
问题描述
I'm parsing in a Json document that stores a list of type <Country>
(which holds the name
and code
), using the MongoDB.Net driver. But I'm not sure how to retrieve that list of countries from the Bson document.
我单步执行了解析代码,所有值都被解析到CountryModel中.然后存储在返回的collection
var中.
I stepped through the parsing code, all values are being parsed in to the CountryModel. Then stored in the returned collection
var.
Google搜索给我带来了此解决方案,但仅显示了如何通过ID返回记录而不是完整列表.我想知道是否可以在这里使用Lambda重载来查找列表.
Googling brought me this solution but it only shows how to return a record by ID not a complete List. I'm wondering if a Lambda overload can be used here to find the list.
到目前为止,我已经设法检索了完整的文档,并将其分配给列表:
So far I've managed to retrieve the complete doc, and assign it to a list :
countries = collection.Find(new BsonDocument()).ToListAsync().GetAwaiter().GetResult();
有人知道我怎么能只获取List<Country>
而不是整个文档?
Does anyone know how I can fetch just List<Country>
and not the whole document?
检索数据涉及的两种主要方法如下:
The two main methods involved in retrieving the data are as follows:
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数据的示例:
This is a sample of the Json data that's parsed in:
{
"_id": {
"$oid": "565f5d3ae4b0ed465284d17a"
},
"countries": [
{
"name": "Afghanistan",
"code": "AF"
},
{
"name": "Antigua and Barbuda",
"code": "AG"
}
]
}
这是支持POCO的类,CountryModel
:
And this is the backing POCO class, 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.
Where {ObjectId} is the id of the CountryModel from which you want to fetch the countries collection.
顺便说一句:有一种使用ObjectId
的更方便的方法.您可以在模型中放置string
并添加属性:
Btw: There is more convenient way for using ObjectId
. You can place string
in your model and add attributes:
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
然后您可以将Find
与string
中的ID一起使用:
Then you can use Find
with Id in string
:
collection.Find(x => x.Id == "sample_object_id")
这篇关于如何从Bson文档中获取值列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!