简体   繁体   中英

Fetch 3 days data from mongoDB using python

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'

}

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM