我有一个MongoDb文档集合,每个文档包含一组嵌入式文档。我想检索其date属性在给定日期之前的那些嵌入式文档的拼合列表。
假设我们有以下类:
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'与类'Reservation'的任何字段或属性都不匹配
因此,我添加了一个投影。如果仅排除_id字段,则会得到:
“元素”已创建”与“预订”类的任何字段或属性都不匹配
因此,我手动添加了其他字段(应该没有必要):
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的名称设置为null,日期设置为1/1/0001。
如何检索其集合中date属性早于/小于给定日期的所有预订的扁平化列表?
我想如果你用
collection.AsQueryable().SelectMany(s => s.Reservations).Where(r => r.Date > thresholdDate).ToList();
它应该返回您的期望。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句