在 MongoDB 中的文档 属性 上使用过滤器获取嵌入数组中的扁平化文档数组

Get flattened array of documents embedded in array with filter on document property in MongoDB

我有 MongoDb collection 个文档,每个文档都包含一组嵌入式文档。我想检索日期 属性 在给定日期之前的那些嵌入文档的扁平化列表。

假设我们有以下 classes:

public class RootItem
{
    public string Id { get; set; }
    public string Name{ get; set; }
    public string PictureUrl { get; set; }
    public List<Reservation> Reservations { get; set; }
}

public class Reservation
{
    public string Name { get; set; }
    public DateTime Date{ get; set; }
    public int NrOfSeats { get; set; }
}

所以 collection 看起来像这样:

{
  "_id": "5be2bb2fdfd6174938518af2",
  "name": "John Doe",
  "pictureUrl": "http://example.com/abc.jpg",
  "reservations": [
    {
      "table": "abc",
      "date": "1/1/2019",
      "nrOfSeats": 5
    },
    {
      "name": "xyz",
      "date": "7/1/2019",
      "nrOfSeats": 5
    }
  ]
}

我已经阅读了文档,我已经在 SO 上阅读了很多,但到目前为止我最接近的是:

var reservations = Collection
            .Aggregate()
            .Unwind<RootItem, Reservation>(x => x.Reservations)
            .ToList()
            .FindAll(r => r.Date > thresholdDate);

运行 这段代码我得到了这个错误:

System.FormatException: '元素 '_id' 不匹配 class 的任何字段或 属性 'Reservation'

所以我加了一个投影。如果我只排除 _id 字段,我会得到:

'元素'Created'不匹配class的任何字段或属性'Reservation'

所以我手动包含其他字段(应该是不必要的):

var reservations = Collection
            .Aggregate()
            .Unwind<RootItem, Reservation>(x => x.Reservations)
            .Project<Reservation>(Builders<Reservation>.Projection
                 .Exclude("_id")
                 .Include(r => r.Name)
                 .Include(r => r.Date)
                 .Include(r => r.NrOfSeats))
            .ToList()
            .FindAll(r => r.Date > thresholdDate);

但现在我得到一个列表,其中 NrOfSeats 和名称设置为空,日期设置为 1/1/0001。

如何检索我的 collection 中日期 属性 比给定日期 before/smaller 的所有预订的扁平化列表?

我想如果你使用

collection.AsQueryable().SelectMany(s => s.Reservations).Where(r => r.Date > thresholdDate).ToList();

它应该return如您所愿。