Skip to content

Instantly share code, notes, and snippets.

@awatson1978
Created March 24, 2014 17:03
Show Gist options
  • Save awatson1978/9744515 to your computer and use it in GitHub Desktop.
Save awatson1978/9744515 to your computer and use it in GitHub Desktop.
db.mycollection.find({ _id: { $gt: objectIdWithTimestamp('1980/05/25') } });
// This function returns an ObjectId embedded with a given datetime
// Accepts both Date object and string input
function objectIdWithTimestamp(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
}
// Find all documents created after midnight on May 25th, 1980
db.mycollection.find({ _id: { $gt: objectIdWithTimestamp('1980/05/25') } });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment