'MongoDB Driver Builders<dynamic> dont work on equal to date

I am unable to get the result I wanted when I try to get Date equal to.

FilterDefinition<dynamic> searchFilter = FilterDefinition<dynamic>.Empty;
string x = "system_create_date";
string y = "2021-11-08";   
var SearchDAte = DateTime.Parse(y, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);
searchFilter &= Builders<dynamic>.Filter.Eq(x, SearchDAte);

Nothing returns as a result.

I wonder what I have done wrong.



Solution 1:[1]

As the provided code, the date comparison (Eq) will be included with Time.

AFAIK, I don't think it is doable to directly compare Date only in MongoDB unless the particular date field is without time value (Example: 2021-11-08T00:00:00.000+00:00).


Solution 1: Compare date within the range

Since you want to query the document(s) within one day (system_create_date), hence:

Start Date: 2021-11-08 (greater than or equal to)

End Date: 2021-11-09 (less than)

FilterDefinition<dynamic> searchFilter = FilterDefinition<dynamic>.Empty;
string x = "system_create_date";
string y = "2021-11-08";
string z = "2021-11-09";

var startDate = DateTime.Parse(y, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);
var endDate = DateTime.Parse(z, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);

searchFilter &= Builders<dynamic>.Filter.Gte(x, startDate);
searchFilter &= Builders<dynamic>.Filter.Lt(x, endDate);

Solution 2: With BsonDocument

With BsonDocument, you can compare date only by converting system_create_date to date string.

BsonDocument filterDoc = new BsonDocument("$expr", 
    new BsonDocument("$eq",
        new BsonArray
        {
            new BsonDocument("$dateToString",
            new BsonDocument
            {
                { "format", "%Y-%m-%d" },
                { "date", "$system_create_date" }
            }),
            "2021-11-08"
        }
    )
);

FilterDefinition<dynamic> searchFilter = FilterDefinition<dynamic>.Empty;
searchFilter &= filterDoc;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yong Shun