Skip to content

Instantly share code, notes, and snippets.

@johannesl
Last active April 13, 2016 07:41
Show Gist options
  • Save johannesl/23ca3c82a0be8e557d270b30f4952533 to your computer and use it in GitHub Desktop.
Save johannesl/23ca3c82a0be8e557d270b30f4952533 to your computer and use it in GitHub Desktop.
How to get documents from MongoDB within a specific date or time range using default ObjectId indexes
import time
from datetime import datetime
def mongoDatetimeToObjectId(dt):
return '%08x0000000000000000' % time.mktime(dt.timetuple())
# Allows doing queries based on creation time without a specific index
day1 = datetime(2016,1,1)
day2 = datetime(2016,2,1)
conn.collection.query({'_id':{'$gt':mongoDatetimeToObjectId(day1),'$lt':mongoDatetimeToObjectId(day2)}})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment