问题
I am trying to fetch 3 days old data from mongoDB using python (pymongo).
I am quite new to mongodb. How to do this ?.Thanks in advance.
My db entries are following :
{
"_id" : ObjectId("5d720d1d9c338906de2dbc812"),
"timestamp" : ISODate("2019-11-12T08:00:00Z"),
"city" : 'abc'
}
{
"_id" : ObjectId("5d720d1d9c338906de2dbc813"),
"timestamp" : ISODate("2019-11-11T09:00:00Z"),
"city" : 'xyz'
}
{
"_id" : ObjectId("5d720d1d9c338906de2dbc84"),
"timestamp" : ISODate("2019-07-18T06:00:00Z"),
"city": 'pqr'
}
{
"_id" : ObjectId("5d720cb29c338906dd2d4ea1"),
"timestamp" : ISODate("2019-11-11T07:00:00Z"),
"city" : 'pqr'
}
回答1:
Just use gt(e) & lt(e) operators with datetime objects, pymongo will handle the rest itself:
#import pymongo
# ...
import datetime
end = datetime.datetime.utcnow()
start = end - datetime.timedelta(days=3)
cursor = db.collection.find({
'timestamp' : {'$gte': start, '$lte': end}
})
for item in cursor:
print(item)
来源:https://stackoverflow.com/questions/58841132/fetch-3-days-data-from-mongodb-using-python