MongoDB - Querying between a time range of hours

前端 未结 2 546
攒了一身酷
攒了一身酷 2020-11-30 10:31

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

{
\"_id\" : ObjectId(\"51d3e161ce87bb000792dc8d\"),
\"datetime_recorded\" : ISODate(\"         


        
2条回答
  •  感动是毒
    2020-11-30 11:18

    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 } } }
    ] );
    

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

提交回复
热议问题