Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query MongoDB search only in specific hours [duplicate]

i have a question, i want to search by specific hours of the day,

Lets start:

My data schema sees like this:

{
 "symbol": "Orange",
 "timestamp": ISODate("2016-05-01T20:00:00.000Z"),
 "price": 10
}

I have a lot of entries, and the value of price change minute by minute.

If i want to search, let's say, all days when the hours of the day are: 9 or 15, so the result must return all the entries 9 to 9:59 and 15 to 15:59

I try to do something like:

 { $match: { timestamp: { $hour: { $in: [array_hours] } } }

But obviously, don't work.

Any ideas?

like image 865
MatCas Avatar asked Jun 14 '16 23:06

MatCas


1 Answers

I think you can use $hour, $day ... to break down the date in aggregation. For example:

my data:

db.orders.find()
{ "_id" : ObjectId("5760bf21b05d6825e05fa23d"), "item" : "test1", 
          "create_at" : ISODate("2016-04-30T11:00:00Z") }
{ "_id" : ObjectId("5760bf30b05d6825e05fa23e"), "item" : "test2", 
          "create_at" : ISODate("2016-04-30T12:00:00Z") }
{ "_id" : ObjectId("5760bf37b05d6825e05fa23f"), "item" : "test3",  
          "create_at" : ISODate("2016-04-30T13:00:00Z") }

my query:

db.orders.aggregate([{$project:{hour:{$hour:"$create_at"}}}, 
                 {$match:{hour:{"$in":[11,12]}}}])
{ "_id" : ObjectId("5760bf21b05d6825e05fa23d"), "hour" : 11 }
{ "_id" : ObjectId("5760bf30b05d6825e05fa23e"), "hour" : 12 }

Here is the doc

like image 133
Leo Avatar answered Sep 20 '22 20:09

Leo