Search code examples
c#mongodbmongodb-.net-driver

Find documents in mongodb by Date field + some date value


I Need some help with C# Mongo Driver and mongodb.

C# class example:

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

    public DateTime StartTime { get; set; }

    public TimeSpan CustomPeriod { get; set; }
 }

I need a way to find documents in mongodb by StartTime field + some TimeSpan value, like this predicate:

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

These predicates are not working and I am getting an error when executing Collection.Find() query now:

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


Solution

  • The issue is the query language used by the underlying find command at the MongoDB instance does not support comparing one field in a document with another, or performing operations on these fields before comparison.

    The $expr operator permits using aggregation expressions, but you usually forfeit the ability to use an index for that portion of the query.

    In the mongo shell that might look like:

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

    I'm not familiar with C#, so I don't know how to express that using the .net driver