MongoDB - search by date and time using C # driver

Hello, I want to find entries between two dates (over time) using the C # driver for MongoDB, but the Find + Filter method that I use ignores the time and searches only by date (I think). What am I doing wrong?

My POCO:

public class TestClassForMongo
{
    public ObjectId Id { get; set; }
    public DateTime CreatedDateUtc { get; set; }
    public string Message { get; set; }
}

My search code:

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();

The above code returns an empty array, although this is:

collection.Find(filterBuilder.Empty).First().CreatedDateUtc

Returns the date: "2016-03-04 21:21:54"

MongoDB 3.2.3, C # MongoDB driver 2.2.3

Driver docs: https://docs.mongodb.org/getting-started/csharp/query/

ANSWER:

, - , , UTC, . DateTime.UtcNow . "CreatedDateUtc" : ISODate("2016-03-04T21:21:54.836Z"). # , UTC ( Kind UTC), btw 'Z' db. UTC DateTime() , , +0 (UTC).

, :

 new DateTime(2016, 03, 04, 21, 0, 0).ToUniversalTime()

, , 1 ( +1).

, 22:21:54 . 22:00:00 23:00:00, , , .

+4
1

BSON dateTime (. ),

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 :

linqPad dump

+3

All Articles