2

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?

Gabriel Petrovay
  • 18,575
  • 19
  • 87
  • 153

1 Answers1

6

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));
robertklep
  • 185,685
  • 31
  • 370
  • 359