0

I want to get new elements added to a MongoDB collection within the last 24 hours. My scripts are in Python so I'm using pymongo library.

I've tried:
yesterday_datetime = datetime.datetime.now() - datetime.timedelta(days=1) # datetime.datetime(2023, 1, 2, 10, 53, 47, 667989)
collection.find_one({"DbCreateDate": {'gt': yesterday_datetime}})
But the output is:
None

I know there is a new element. When I do:
collection.find_one({"DbCreateDate": datetime.datetime(2023, 1, 3, 0, 0)})
It outputs:
{'_id': 'FAKE_01', 'DbCreateDate': datetime.datetime(2023, 1, 3, 0, 0)}

I've also tried
collection.find_one({"DbCreateDate": {'gt': datetime.datetime(2022, 12, 31, 0, 0)}}) collection.find_one({"DbCreateDate": {'gte': datetime.datetime(2022, 1, 1, 0, 0)}}) collection.find_one({"DbCreateDate": {'gt': datetime.datetime(2022, 12, 31, 0, 0).isoformat()}}) Always output None.

JulienBr
  • 53
  • 7
  • What does `collection.find_one` without any filter return? What is the format of the stored value? If it is a string, gt will not work! – Mafii Jan 03 '23 at 10:59
  • collection.find_one without any filter returns `{'_id': 'FAKE_01', 'DbCreateDate': datetime.datetime(2020, 4, 6, 0, 0)}` The output is a dictionary and the value of the DbCreateDate key is a datetime. – JulienBr Jan 03 '23 at 11:10
  • see https://stackoverflow.com/a/2943685/5962841 - I think you need to serialize it in a specific way :) – Mafii Jan 03 '23 at 11:16

1 Answers1

0

Solved:

I needed to add a $ when creating the filter, before gt:

collection.find_one({"DbCreateDate": {'$gt': yesterday_datetime}})
JulienBr
  • 53
  • 7