簡體   English   中英

如何從Bson文檔中獲取值列表?

[英]How to fetch a list of values from a Bson document?

我正在使用MongoDB.Net驅動程序在Json文檔中解析,該文檔存儲類型<Country> (包含namecode )的列表 但我不確定如何從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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM