MongoDB和DateTimeOffset类型 [英] MongoDB and DateTimeOffset type

查看:129
本文介绍了MongoDB和DateTimeOffset类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找在指定时间内创建的所有文档. 我正在使用c#和mongodb c#驱动程序.

I am trying to find all documents that are created within a specified time. I am using c# and the mongodb c# driver.

我的实体如下:

public class Entity
{
    public Gid Id { get; private set; }
    public DateTimeOffset CreationTimestamp { get; private set; }
    public Entity()
    {
    }
}

所以我想我可以做到:

DateTime compareTime = DateTime.UtcNow.AddMinutes(-15);
var result = _collection.Find(Query.GT("CreationTimestamp", compareTime)).Count();

即使集合中有数据,结果也是零计数. 如果从DateTimeOffset更改为DateTime,我将返回结果.

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.

是否不支持DateTimeOffset类型的问题? 如果可以的话,有没有办法解决此问题,因为我需要我的实体使用DateTimeOffset吗?

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根本没有序列化为Date,而是(默认情况下)序列化为[ticks,timezone offset]数组.因此,您无法以与正常日期相同的方式查询它.相反,我们将基于刻度进行查询.您需要确保您的时区偏移量相同,否则将无法正常工作.

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.

这篇关于MongoDB和DateTimeOffset类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆