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
  • 20,476
  • 22
  • 97
  • 168

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
  • 198,204
  • 35
  • 394
  • 381
  • Note that for Date you should use a string. The behavior of `new Date(1974, 6, 25)` is somewhat unexpected. You should use `new Date('1974-06-25')` – odedfos Aug 08 '23 at 17:08