1

添加/解释我最近的问题

以下是 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”,因为它在带有deliverynum = 999的“doc”中有最新的“日期”。

我打算这样做:

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

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

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

4

1 回答 1

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();
于 2019-07-25T13:10:49.413 回答