I am trying to find all documents that are created within a specified time. I am using c# and the mongodb c# driver.
My entity is as follows:
public class Entity
{
public Gid Id { get; private set; }
public DateTimeOffset CreationTimestamp { get; private set; }
public Entity()
{
}
}
So I thought I could do this:
DateTime compareTime = DateTime.UtcNow.AddMinutes(-15);
var result = _collection.Find(Query.GT("CreationTimestamp", compareTime)).Count();
Result is a count of zero even though there is data in the collection. If I change from DateTimeOffset to DateTime I will get back a result.
Is the issue that DateTimeOffset type is not supported? If so is there a way around this as I need my entities to use DateTimeOffset?
DateTimeOffset is not serialized as a Date at all, but (by default), as an array of [ticks, timezone offset]. As such, you cannot query it the same way you would a normal date. Instead, we'll query based on the ticks. You'll need to make sure your timezone offsets are the same, otherwise this won't work.
DateTimeOffsett compareTime = DateTimeOffsett.UtcNow.AddMinutes(-15);
var result = _collection.Find(Query.GT("CreationTimestamp.0", compareTime.Ticks)).Count();
Basically, we are going to compare the first element of the stored array with the tick count. Sorry again for the time it took to arrive at this answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With