MongoDb find collection document based on timestam

2019-08-27 13:09发布

问题:

I have user profile data as:

    {u'DOB': None,
    u'_id': ObjectId('5906f3b.....'),
    u'active': 0,
    u'bfunc': 0,
    u'city': None,
    u'contact': u'',

u'created': 1493627839,

    u'email': u'mymail@demo.c
    u'facebook_id': u'',
    u'fburl': None,
    u'firstname': u'',
    u'gender': None,
    u'group_id': None}

I want to find all data between last 4 hrs based on created field.

Current created value is 1493627839 which is 2017-05-01 14:07:19

I want to find lessthan current time and greaterthan last 4 hrs. How could i find value based on datetime.

Should i convert current time into timestamp then find or something else?

I did this but it returned 0 as my values stored in timestamp format.

   value = []
    cursor = collection.find({
        'created': {
            "$gte": datetime.datetime.now(),
            "$lt": datetime.datetime.now() - datetime.timedelta(days=5)
        }
    })

how could i query it.

Note: I am storing values in php but this query is fired in 'python 2.7'.

Edit:

   value = []
    cursor = collection.find({
        'created': {
            "$lt": datetime.datetime.now(),
            "$gte": datetime.datetime.now() - datetime.timedelta(days=5)
        }
    })

but still find query is empty

回答1:

You are using opposite condition , use as follow

timenow=datetime.datetime.now();
ltunix = timenow.strftime('%s');  //convert to timestamp

gteTime= timenow- datetime.timedelta(hours=4);
getTimeUnix=gteTime.strftime('%s');  //convert to timestamp

cursor = collection.find({
            'created': {
                "$lt": ltunix,
                "$gte": getTimeUnix
            }
        })