您好,我想使用 MongoDB 的 C# 驱动程序查找两个日期(带时间)之间的条目,但我使用的 Find + Filter 方法忽略了时间并仅按日期搜索(我认为)。我做错了什么?
我的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 日期与新的 DateTime() 进行比较没有多大意义,因为后者会在您的时区创建一个日期,该日期可能不同于 +0 (UTC)。
因此,一种选择是像这样为过滤器创建日期:
new DateTime(2016, 03, 04, 21, 0, 0).ToUniversalTime()
或者修改小时部分以适应时区差异,在我的示例中它将增加 1 小时(因为我处于 +1 时区)。
所以实际上存储的时间是我所在时区的 22:21:54
。如果我使用在我的时区创建的日期在 22:00:00 和 23:00:00 之间进行搜索,我会得到正确的结果。
最佳答案
在日期时间字段上添加 BSON 属性(见下文),
您可以使用 linqu 语法来构建这样的查询
var min = new DateTime(2016, 03, 03, 22, 0, 0);
var max = (new DateTime(2016, 03, 03, 23, 0, 0));
List<TestClassForMongo> searchResult = collection.Find(
x => x.CreatedDateUtc > min &
x.CreatedDateUtc < max
).ToList();
BSON ATTRIBUTE
public class TestClassForMongo
{
public ObjectId Id { get; set; }
[BsonDateTimeOptions]
public DateTime CreatedDateUtc { get; set; }
public string Message { get; set; }
}
linqPad dump below:
关于c# - MongoDB - 使用 C# 驱动程序按日期和时间搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35819552/