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?

1 Answer 1

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));
Sign up to request clarification or add additional context in comments.

1 Comment

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')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.