Search code examples
javascriptmongodbmongo-shell

How to create an ObjectId from a Date value in the mongo shell?


I want to create a new ObjectId in the mongo shell but for a Date in the past in order to simulate the creation ob this document in the past. That would be the opposite of the getTimestamp() function of an ObjectId (i.e. give a timestamp, get an ObjectId that returns that timestamp when calling getTimestamp on it)

Any ideas how to do this?


Solution

  • The Mongo shell doesn't seem to support this explicitly. But apart from some timezone stuff, this works:

    var timestamp = Math.floor(new Date(1974, 6, 25).getTime() / 1000);
    var hex       = ('00000000' + timestamp.toString(16)).substr(-8); // zero padding
    var objectId  = new ObjectId(hex + new ObjectId().str.substring(8));