MongoDB - 在几个小时的时间范围内查询 [英] MongoDB - Querying between a time range of hours

查看:28
本文介绍了MongoDB - 在几个小时的时间范围内查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设置了一个 MongoDB 数据存储,其中的位置数据存储如下:

I have a MongoDB datastore set up with location data stored like this:

{
"_id" : ObjectId("51d3e161ce87bb000792dc8d"),
"datetime_recorded" : ISODate("2013-07-03T05:35:13Z"),
"loc" : {
    "coordinates" : [
        0.297716,
        18.050614
    ],
    "type" : "Point"
},
"vid" : "11111-22222-33333-44444"
}

我希望能够执行类似于 日期范围 示例的查询而是在时间范围.即检索上午 12 点到下午 4 点之间记录的所有点(也可以使用 1200 和 1600 24 小时时间完成).

I'd like to be able to perform a query similar to the date range example but instead on a time range. i.e. Retrieve all points recorded between 12AM and 4PM (can be done with 1200 and 1600 24 hour time as well).

例如

有积分:

  • "datetime_recorded" : ISODate("2013-05-01T12:35:13Z"),
  • "datetime_recorded" : ISODate("2013-06-20T05:35:13Z"),
  • "datetime_recorded" : ISODate("2013-01-17T07:35:13Z"),
  • "datetime_recorded" : ISODate("2013-04-03T15:35:13Z"),

查询

db.points.find({'datetime_recorded': {
    $gte: Date(1200 hours),
    $lt: Date(1600 hours)}
});

只会产生第一个和最后一个点.

would yield only the first and last point.

这可能吗?还是我必须每天都这样做?

Is this possible? Or would I have to do it for every day?

推荐答案

嗯,解决这个问题的最好方法是将会议记录分开存储.但是您可以使用聚合框架来解决这个问题,尽管这样不会非常快:

Well, the best way to solve this is to store the minutes separately as well. But you can get around this with the aggregation framework, although that is not going to be very fast:

db.so.aggregate( [ 
    { $project: {
        loc: 1,
        vid: 1,
        datetime_recorded: 1, 
        minutes: { $add: [
            { $multiply: [ { $hour: '$datetime_recorded' }, 60 ] }, 
            { $minute: '$datetime_recorded' } 
        ] } 
    } },
    { $match: { 'minutes' : { $gte : 12 * 60, $lt : 16 * 60 } } }
] );

在第一步 $project 中,我们根据 hour * 60 + min 计算分钟,然后在第二步中匹配:$match.

In the first step $project, we calculate the minutes from hour * 60 + min which we then match against in the second step: $match.

这篇关于MongoDB - 在几个小时的时间范围内查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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