Created
September 10, 2013 16:24
-
-
Save aaronup/6511899 to your computer and use it in GitHub Desktop.
Create an ObjectID with a timestamp for MongoDB Created date queries
This file contains hidden or 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
| function ObjectIDTS(timestamp) { | |
| // Convert string date to Date object (otherwise assume timestamp is a date) | |
| if (typeof(timestamp) == 'string') { | |
| timestamp = new Date(timestamp); | |
| } | |
| // Convert date object to hex seconds since Unix epoch | |
| var hexSeconds = Math.floor(timestamp/1000).toString(16); | |
| // Create an ObjectId with that hex timestamp | |
| var constructedObjectId = ObjectId(hexSeconds + "0000000000000000"); | |
| return constructedObjectId; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage example
db.collection.find({ _id: { $gt: ObjectIDTS('YYYY/MM/DD') } });