按日期字段 + 一些日期值查找 mongodb 中的文档

Find documents in mongodb by Date field + some date value

我需要一些有关 C# Mongo 驱动程序和 mongodb 的帮助。

C# class 示例:

 public class Document
 {
    public string Id { get; set; }

    public DateTime StartTime { get; set; }

    public TimeSpan CustomPeriod { get; set; }
 }

我需要一种通过 StartTime 字段 + 一些 TimeSpan 值在 mongodb 中查找文档的方法,就像这个谓词:

Expression<Func<Document, bool>> customExpression = x 
    => x.StartTime.Add(x.CustomPeriod) <= DateTime.UtcNow;

这些谓词不起作用,现在执行 Collection.Find() 查询时出现错误:

{document}{StartTime}.Add({document}{CustomPeriod}) is not supported.

问题是 MongoDB 实例中的底层 find 命令使用的查询语言不支持将文档中的一个字段与另一个字段进行比较,或者在比较之前对这些字段执行操作。

$expr 运算符允许使用聚合表达式,但您通常会丧失为该部分查询使用索引的能力。

在 mongo shell 中可能看起来像:

db.collection.find({
      $expr:{
         $gte:[ 
            new Date(), 
            {$add: [ "$StartTime", "$CustomPeriod"]}
         ]
      }
})

我不熟悉 C#,所以我不知道如何使用 .net 驱动程序表达它