MongoDB - 使用 C# 驱动程序按日期和时间搜索

use*_*059 6 c# mongodb

您好,我想使用 MongoDB 的 C# 驱动程序查找两个日期(带时间)之间的条目,但是我使用的 Find + Filter 方法忽略了时间并仅按日期搜索(我认为)。我究竟做错了什么?

我的POCO:

public class TestClassForMongo
{
    public ObjectId Id { get; set; }
    public DateTime CreatedDateUtc { get; set; }
    public string Message { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我的搜索代码:

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();
Run Code Online (Sandbox Code Playgroud)

上面的代码返回空数组,尽管这样:

collection.Find(filterBuilder.Empty).First().CreatedDateUtc
Run Code Online (Sandbox Code Playgroud)

返回日期:“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()
Run Code Online (Sandbox Code Playgroud)

或者修改小时部分以适应时区差异,在我的示例中将增加 1 小时(因为我在 +1 时区)。

所以实际上存储的时间22:21:54在我的时区。如果我使用在我的时区中创建的日期在 22:00:00 和 23:00:00 之间进行搜索,我会得到正确的结果。

pro*_*r79 5

在 dateTime 字段上添加 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();
Run Code Online (Sandbox Code Playgroud)

BSON 属性

public class TestClassForMongo
{
    public ObjectId Id { get; set; }

    [BsonDateTimeOptions]
    public DateTime CreatedDateUtc { get; set; }

    public string Message { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

linqPad 转储如下:

linqPad 转储