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

Querying a subfield in DocumentDB to sort and get the latest date

我最近

add/expound

以下是 DocumentDB 集合:"delivery"

{
    "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”,因为它在 [= 中有最新的 "date" 28=] w/ deliverynum=999。

我打算做的:

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

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

正在寻找获取刚需 "id" 或获取单个文档的方法。

我相信以下内容可以解决问题。 (如果我理解正确的话)

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();