[英]How do I get C# Mongo driver to compare a DateTime field using Linq expressions?
I am creating a select query to pass to MongoDB using Linq Expressions.我正在创建一个 select 查询以使用 Linq 表达式传递给 MongoDB。
I want to query the collection for documents with a DateTimePosed
< a given date.我想查询集合中包含
DateTimePosed
< 给定日期的文档。 (The repository
variable is an IQueryable
derived from IMongoCollection.AsQueryable()
): (
repository
变量是从IMongoCollection.AsQueryable()
派生的IQueryable
):
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:当我在 mongo 客户端中运行它时,它返回 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?你能告诉我我做错了什么吗?
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.我必须将有效的日期时间值作为字符串传递,才能使比较生效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.