I am trying to query a collection by date only to check if a corresponding record exist. I have tried a number of solution here and google searches but no success. How can i also save date and time to local time.
Sample Collection
{
"_id" : ObjectId("5a4f8026762caf03f0a22114"),
"AttnDate" : ISODate("2018-01-04T20:00:00.000Z"),
"AllAttendances" : [
{
"FullName" : "MYDOMAIN\\Michelle",
"Logged" : ISODate("2018-01-05T13:39:35.338Z"),
"IdleTime" : 17
}
]
}
Attendance Class
public class Attendance
{
[JsonConverter(typeof(ObjectIdConverter))]
public ObjectId Id { get; set; }
[BsonDateTimeOptions(Kind = DateTimeKind.Local)]
public DateTime AttnDate { get; set; }
public IEnumerable<TimeRecord> AllAttendances { get; set; }
}
The Query method
public Attendance FindAttendanceByDate(DateTime CurrentDate)
{
var filter = Builders<Attendance>.Filter.Eq(x => x.AttnDate, CurrentDate);
return context.Attendances.Find(filter).FirstOrDefault();
}
How i am passing the CurrentDate on the above method
_AttendancesRepositories.FindAttendanceByDate(DateTime.Today);
Solution
In my case, i had to disable "Set time automatically" and "Set time zone automatically" in windows setting to get this to work. I dont know why. I may help someone to save 12 hours of their life.
var start = CurrentDate; var ending = CurrentDate.AddDays(1); var filterbuilder = Builders<Attendance>.Filter; var fil = filterbuilder.Gte(x => x.AttnDate, start) & filterbuilder.Lt(x => x.AttnDate, ending); return context.Attendances.Find(fil).FirstOrDefault();the method is still returning null.var start = new DateTime("2018-01-05"); var ending = new DateTime("2018-01-06");The idea is to not include the time part or set to all zeros.