【问题标题】:Get flattened array of documents embedded in array with filter on document property in MongoDB使用 MongoDB 中的文档属性过滤器获取嵌入数组中的扁平文档数组
【发布时间】:2019-06-26 23:40:01
【问题描述】:

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

假设我们有以下类:

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; }
}

所以集合看起来像这样:

{
  "_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”与“预订”类的任何字段或属性都不匹配

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

'元素'Created'不匹配'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 和 Name 设置为 null,Date 设置为 1/1/0001。

如何检索我的集合中日期属性早于/小于给定日期的所有预订的扁平列表?

【问题讨论】:

    标签: c# .net mongodb mongodb-query mongodb-.net-driver


    【解决方案1】:

    我想如果你使用

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

    它应该返回你所期望的。

    【讨论】:

    • 太棒了,正是我想要的!谢谢;-)
    猜你喜欢
    • 1970-01-01
    • 2018-01-26
    • 2020-11-22
    • 2022-01-11
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多