Did you know that each MongoDB ObjectId contains an embedded timestamp of its creation time?
From the mongo shell, you can use getTimestamp() to retrieve the timestamp from the ObjectId, but there's no built in function to generate an ObjectId from a timestamp.
This online converter will convert from timestamp to ObjectId and vice versa.
Year (XXXX) | |
Month (1 - 12) | |
Date (1 - 31) | |
Hours | |
Minutes | |
Seconds | |
ISO Timestamp |
To query documents by creation date.
e.g. to find all users created after 2017-12-01 , here users is a collection in mongodb
db.users.find({_id: {$gt: ObjectId("5a204e280000000000000000")}})
var objectIdFromDate = function (date) {
return Math.floor(date.getTime() / 1000).toString(16) + "0000000000000000";
};
var objectIdFromDate = function (date) {
return Math.floor(date.getTime() / 1000).toString(16) + "0000000000000000";
};
var dateFromObjectId = function (objectId) {
return new Date(parseInt(objectId.substring(0, 8), 16) * 1000);
};