Last active
April 13, 2016 07:41
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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