Skip to content

Instantly share code, notes, and snippets.

@aaronup
Created September 10, 2013 16:24
Show Gist options
  • Select an option

  • Save aaronup/6511899 to your computer and use it in GitHub Desktop.

Select an option

Save aaronup/6511899 to your computer and use it in GitHub Desktop.
Create an ObjectID with a timestamp for MongoDB Created date queries
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;
}
@aaronup
Copy link
Author

aaronup commented Sep 12, 2013

Usage example
db.collection.find({ _id: { $gt: ObjectIDTS('YYYY/MM/DD') } });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment