MongoDB and DateTimeOffset type

泄露秘密 提交于 2019-12-22 04:33:21

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/10480127/mongodb-and-datetimeoffset-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!