【发布时间】:2014-03-01 13:39:34
【问题描述】:
我有一个 MongoDB 数据库来存储记录,这些记录具有创建时间的时间戳和值。我使用官方 C# 驱动程序连接并查询该数据库。
一个正常的用例涉及获取 >= startDateTime 和
但是,有时数据点距离周期的开始和结束足够远,我需要在 startDateTime 和 endDateTime 处插入值。为此,我显然需要 startDateTime 之前的最后一条记录,以及 endDateTime 之后的第一条记录。使用三个查询很容易做到这一点,但我想避免这种情况以减少到数据库的往返次数。
是否可以通过单个查询来实现?
编辑:因为我被要求澄清用例:
假设我有一个每小时记录一次温度的传感器。温度和时间戳存储在 MongoDB 集合中。现在,我想绘制昨天的温度图,所以我询问所有时间戳 >= 2014.02.04 00:00:00 且时间戳 的记录
事实证明,这个传感器每小时记录 55 分钟,所以我的第一个数据点是昨天的 55 分钟,而我的最后一个数据点是昨天结束的 5 分钟。
除了我的时间范围内的 24 个值之外,我还想获取 2014.02.03 23:55:00 和 2014.02.05 00:55:00 的值,以便进行插值。这需要概括为获取月经开始前的最后一条记录和月经结束后的第一条记录,因为我无法知道传感器记录的频率、记录时间或是否离线在任何时候。
Edit2:我现在的代码的缩写版本:
//Get last record before the period
var cursor = collection.Find(
Query.LT("DateTime", startDateTime)
);
cursor.Limit = 1;
cursor.SetSortOrder(SortBy.Descending("DateTime"));
//Not shown: getting the record from the cursor and adding it to the collection
//Getting all records that fall within the specified period
cursor = collection.Find(
Query.And(
Query.GTE("DateTime", startDateTime),
Query.LTE("DateTime", endDateTime))
);
//Not shown: getting the records from the cursor and adding them to the collection
//Get first record after the period
cursor = collection.Find(
Query.GT("DateTime", endDateTime)
);
cursor.Limit = 1;
cursor.SetSortOrder(SortBy.Ascending("DateTime"));
//Not shown: getting the record from the cursor and adding it to the collection
【问题讨论】:
-
我从未使用过 MongoDB。在 SQL Server 中,您可以使用几个 UNION 将这三个查询组合成一个。 MongoDB 是否支持 UNION 或等价物?
-
是的,我也最熟悉 SQL。看起来可以使用 OR 运算符:stackoverflow.com/questions/14924129/…
-
不确定我是否理解您的用例。您是说您正在尝试查找要在另一个查询中使用的开始日期和结束日期吗?如果您在问题中发布您实际在做什么的详细信息以进行澄清,这可能会有所帮助。
-
我用一个例子更新了 OP,希望能阐明我在寻找什么。
-
假设您有一个递增的 ID,简单的解决方案是获取该范围内的结果,然后在语法上,获取前面的一个和后面的一个 ...
标签: c# mongodb mongodb-.net-driver