Reputation: 1
DateTime currentDate = DateTime.Now.Date;
DateTime nextDate = currentDate.AddDays(1);
var filter1 = Builders.Filter.Gte(td => td.Txn_Date, currentDate) & Builders.Filter.Lt(td => td.Txn_Date, nextDate);
long count = _dbContext.TransactionDetails.CountDocuments(filter1);
This is my code but with current date it takes some data of previous date.
I tried doing with different method and with different dates. I just want count of current date.
Upvotes: 0
Views: 37
Reputation: 1924
I've somehow successfully replicated the issue on my machine. According to your code, when you render the query, you will observe the following output:
{
"Txn_Date": {
"$gte": ISODate("2023-10-06T18:30:00Z"),
"$lt": ISODate("2023-10-07T18:30:00Z")
}
}
I believe the problem lies with the usage of currentDate
. To address this, I've made a modification by replacing currentDate
with DateTime.Now
, and I've applied the filter as follows: Builders.Filter.Eq(td => td.Txn_Date, currentDate)
.
Below, you can find the complete code (please note that the order used in the code is hypothetical):
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
using System;
public class Program
{
public static void Main()
{
DateTime currentDate = DateTime.Now;
// DateTime nextDate = currentDate.AddDays(1);
var filter1 = Builders<Order>.Filter.Eq(td => td.Txn_Date, currentDate);
var documentSerializer = BsonSerializer.SerializerRegistry.GetSerializer<Order>();
var renderedFilter = filter1.Render(documentSerializer, BsonSerializer.SerializerRegistry);
Console.WriteLine(renderedFilter);
// long count = _dbContext.TransactionDetails.CountDocuments(filter1);
}
}
internal class Order
{
public DateTime Txn_Date { get; set; }
}
Now, it filters based on the current date as demonstrated below:
{
"Txn_Date": ISODate("2023-10-07T11:51:05.968Z")
}
This should resolve the issue.
Upvotes: 0