How do I get C# Mongo driver to compare a DateTime field using Linq expressions?

Viewed 115

I am creating a select query to pass to MongoDB using Linq Expressions.

I want to query the collection for documents with a DateTimePosed < a given date. (The repository variable is an IQueryable derived from IMongoCollection.AsQueryable()):

var parameter = Expression.Parameter(typeof(T), "x");
var finalExpression = Expression.Lambda<Func<T, bool>>(Expression.Constant(true), parameter);
finalExpression.Apply(Expression.LessThan(SomeBusinessObject.DateTimePosted, new DateTime(1988, 2, 1)));
var query = repository.Query;
var results = query.Select(o => o.OfferId.Value).ToList();

When I run the code, the results are empty. When debugging, I see the generated query looks like this:

aggregate([{
    "$match" : { "DateTimePosted" : { "$lt" : "1988-02-01T00:00:00-06:00" } }
}])

When I run this in a mongo client, it returns 0:

db.getCollection('somecollection').aggregate([{
    "$match" : { "DateTimePosted" : { "$lt" : "1988-02-01T00:00:00-06:00" } }
}]);

But if I modify the query like so:

db.getCollection('somecollection').aggregate([{
    "$match" : { "DateTimePosted" : { "$lt" : ISODate("1988-02-01T00:00:00-06:00") } }
}]);

it returns the results.

Can you please tell me what I am doing wrong?

1 Answers

I figured out what was wrong: we are saving the date-time values as strings.

I had to pass in a valid date-time value as a string in order to get the comparison to work.

Related