MongoDB: Only fetch documents created in the last 24hrs?

后端 未结 7 1997
遇见更好的自我
遇见更好的自我 2020-12-03 04:41

I want to limit a query I\'m making to only look in documents that were created in the past 24 hrs.

What is the best way to structure this query? How do I go about

7条回答
  •  攒了一身酷
    2020-12-03 05:17

    Hope this helps someone. I'm using pymongo to query last 24 hours of data. In my case I had to convert the current time into BSON timestamp.

    First I had to import Bson timestamp:

    from bson.timestamp import Timestamp
    

    Then in my search query I did the following:

    yesterday  = datetime.datetime.now() - datetime.timedelta(days=1)
    
    findQuery = {
        "unix": {
            "$gte": Timestamp(int(yesterday.strftime("%s")),0)
         }
    }
    

提交回复
热议问题