查询DocumentDB中的子字段以排序并获取最新日期

时间:2019-07-25 11:46:51

标签: c# mongodb mongodb-.net-driver aws-documentdb

要添加/说明我最近的question

下面是DocumentDB集合:“传递”

{
    "doc": [
        {
            "docid": "15",
            "deliverynum": "123",
            "text": "txxxxxx",
            "date": "2019-07-18T12:37:58Z"
        },
        {
            "docid": "17",
            "deliverynum": "999",
            "text": "txxxxxx",
            "date": "2018-07-18T12:37:58Z"
        }
    ],
    "id": "123",
    "cancelled": false
},
{
    "doc": [
        {
            "docid": "16",
            "deliverynum": "222",
            "text": "txxxxxx",
            "date": "2019-07-18T12:37:58Z"
        },
        {
            "docid": "17",
            "deliverynum": "999",
            "text": "txxxxxx",
            "date": "2019-07-20T12:37:58Z"
        }
    ],
    "id": "124",
    "cancelled": false
}

我需要搜索带有最新日期的deliverynum = 999以获取“ id”,在上述情况下为“ 124”,因为它在带有“ doc”的w / deliverynum = 999中具有最新的“ date” 。

我打算去做

var list = await collection.Find(filter).Project(projection).ToListAsync();

然后执行LINQ排序,但是这里的问题是我的投影将列表从我的模型类更改为BsonDocument,即使我的投影包含所有字段。

正在寻找一种获取所需的“ id”或获取单个文档的方法。

1 个答案:

答案 0 :(得分:1)

我相信以下将解决问题。 (如果我正确理解了您的要求)

var result = collection.Find(x => x.docs.Any(d => d.deliverynum == 999))
                       .Sort(Builders<Record>.Sort.Descending("docs.date"))
                       .Limit(1)
                       .Project(x=>x.Id) //remove this to get back the whole record
                       .ToList();

更新:强类型解决方案

var result = collection.AsQueryable()
                       .Where(r => r.docs.Any(d => d.deliverynum == 999))
                       .SelectMany(r => r.docs, (r, d) => new { r.Id, d.date })
                       .OrderByDescending(x => x.date)
                       .Take(1)
                       .Select(x => x.Id)
                       .ToArray();