您好,我想使用 MongoDB 的 C# 驱动程序查找两个日期(带时间)之间的条目,但我使用的 Find + Filter 方法会忽略时间并仅按日期搜索(我认为)。我究竟做错了什么?
My POCO:
public class TestClassForMongo
{
public ObjectId Id { get; set; }
public DateTime CreatedDateUtc { get; set; }
public string Message { get; set; }
}
我的搜索代码:
IMongoCollection<TestClassForMongo> collection = db.GetCollection<TestClassForMongo>("mongoTest");
var filterBuilder = Builders<TestClassForMongo>.Filter;
var filter = filterBuilder.Gt("CreatedDateUtc", new DateTime(2016, 03, 04, 21, 0, 0)) &
filterBuilder.Lt("CreatedDateUtc", new DateTime(2016, 03, 04, 22, 0, 0));
List<TestClassForMongo> searchResult = collection.Find(filter).ToList();
上面的代码返回空数组,尽管:
collection.Find(filterBuilder.Empty).First().CreatedDateUtc
返回日期:“2016-03-04 21:21:54”
MongoDB 3.2.3、C# MongoDB 驱动程序 2.2.3
驱动程序文档:https://docs.mongodb.org/getting-started/csharp/query/
答案:
我没有提供足够的信息让任何人回答这个问题,问题是时区和UTC相关问题,也很基本。我用了DateTime.UtcNow
将日期存储在数据库中。它存储为"CreatedDateUtc" : ISODate("2016-03-04T21:21:54.836Z")
。在 C# 中获取它会返回一个实际上是 UTC 日期的日期(Kind
财产是UTC
),顺便说一句,它由 db 中值的“Z”后缀表示。将此 UTC 日期与 new DateTime() 进行比较没有多大意义,因为后者在您的时区中创建一个日期,该日期可能与 +0 (UTC) 不同。
因此一种选择是为过滤器创建日期,如下所示:
new DateTime(2016, 03, 04, 21, 0, 0).ToUniversalTime()
或者修改小时部分以适应时区差异,在我的示例中,它将添加 1 小时(因为我位于 +1 时区)。
所以实际上存储的时间是22:21:54
在我的时区。如果我使用在我的时区创建的日期在 22:00:00 和 23:00:00 之间进行搜索,我会得到正确的结果。