Fetch 3 days data from mongoDB using python

99封情书 提交于 2020-01-25 07:05:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!