Created
February 4, 2015 14:45
-
-
Save tebemis/0e55aa0089e928f362d9 to your computer and use it in GitHub Desktop.
Extract object creation timestamps from Mongo object IDs and create Mongo ID with certain timestamps to query date ranges
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
// Cretes a Mongo ID form a timestamp | |
// Useful when we want to query a collection on date ranges | |
function idWithTimestamp(timestamp) { | |
// Convert string or unix time date to Date object (otherwise assume timestamp is a date) | |
if ( typeof(timestamp) == 'string' || typeof(timestamp) == 'number' ) { | |
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 | |
} | |
// Extracts the timestamp an object was created at | |
// from the auto-generated Mongo ID | |
function extractTimestampFrom(id) { | |
return new Date( parseInt( id.toString().substring(0,8), 16 ) * 1000 ); | |
} | |
// Extracts all the objects within a particular dates range in a collection | |
// that are also in a certain channel | |
db.log.find({ _id: { $gt: idWithTimestamp(1422473700000), $lt: idWithTimestamp(1422477900000) }, "channel":"roomquake/new_observation" }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment