MongoDB Tips - Using _id to determine when the object was inserted
MongoDB objectid conversion to timestamp
Basically we can generate timestamp when this document is inserted by converting the objectid to timestamp:
Please look at the following for javascript by Steve Ridout on his blog
https://steveridout.github.io/mongo-object-time/
Basically we can generate timestamp when this document is inserted by converting the objectid to timestamp:
Please look at the following for javascript by Steve Ridout on his blog
https://steveridout.github.io/mongo-object-time/
Why generate an ObjectId from a timestamp?
To query documents by creation date.
e.g. to find all comments created after 2013-11-01:
db.comments.find({_id: {$gt: ObjectId("5272e0f00000000000000000")}})
Javascript functions
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);
};
  
Comments
Post a Comment