Is it possible to calculate the difference between two dates in a document server-side, and query on it? (Like SQL's DATEDIFF
function)
Assume I have a number of documents like this:
>>> db.collection.find()
[
{ "id" : ObjectId("1"),
"starttime" : ISODate("2011-12-01T05:01:00"), # 5:01 AM
"endtime" : ISODate("2011-12-01T05:02:00") # 5:02 AM
},
{ "id" : ObjectId("2"),
"starttime" : ISODate("2011-12-01T06:01:00"), # 6:01:00 AM
"endtime" : ISODate("2011-12-01T06:01:30") # 6:01:30 AM
}
]
Is there a way to achieve something similar to this?
Returning just time difference:
>>> db.collection.date_difference_seconds(endtime, starttime)
[60, 30]
or a query:
>>> db.collection.find("timediff(endtime-starttime) < 40 seconds")
[
{ "id" : ObjectId("2"), ...} # Just second document (30s diff)
]
I've read about server-side JS and eval()
, but the docs say these are not recommended - are they the best option?
(I can obviously add the time difference in seconds as an additional field ("time_diff": 30
), or calculate the differences in Python client-side, but I'd like to know if it's possible server-side)
Client-side calc:
>>> for doc in (collection.find(None, {'starttime': 1, 'endtime': 1 }))
doc['endtime']-doc['startime']
0:01:00.000000
0:00:30.000000
db.collection.find("timediff(endtime-starttime) < 40 seconds")
I thought it was simpler but I didn't think enough about it. Hmmm, there is the possibility of using a$where
here adding the time calc function to that, this would avoid eval but it will seriously reduce speed. I think that if you were to use the aggregation function to make a new computed field using the docs.mongodb.org/manual/reference/aggregation/#date-operators – Sammaye Dec 28 '12 at 15:54