2

how can I get timestamp using object id in MongoDB.I am using NodeJS and mongoDB as my backend service I want to get the date and time of the document when it is inserted in the collection. This is what i am using :

 db.Users.find()._id.getTimestamp()

OUTPUT

 ISODate("2018-09-11T11:00:38Z")

Now, what I want to know is:

1) Separate date and time from above string and convert it into readable format.

2) This timestamp returned by MongoDB object id is based on server time or user's computer.

THANKS

2 Answers 2

2

1) getTimestamp() is available on ObjectID objects, like the _id field by default. So however you are getting your documents will have it available. This returns a javascript Date object, so its easy to extract and manipulate it how you need.

2) The embedded timestamp in the ObjectID is dependent on where it was created. If it was created client-side, it'll be from the client system; if it was created server-side, it'll be from the server system.

Sign up to request clarification or add additional context in comments.

6 Comments

Your first point is cleared to me but in 2nd point how can i set timestamp on server side please let me know.
the only way I know of is the defaulted-_id field, if you create a document without an _id field, the server will generate it for you.
So how can i get time based on _id field.
in nodejs, if you have a document retrieved from mongo, you just do document._id.getTimestamp()
I have document like this {"_id":ObjectId("as244fgv....."),"Name": "Digi"}.So how can i get timestamp for this document.Please let me know .
|
2

1-

.getTimestamp().toLocaleDateString() //get the date
  .getTimestamp().toLocaleTimeString() // get the time

2-Internally, Date objects are stored as a signed 64-bit integer representing the number of milliseconds since the Unix epoch (Jan 1, 1970). One standard way that many databases store dates is as a count of milliseconds since the Epoch, with 0 representing January 1, 1970 at 00:00:00GMT. This is how dates are stored internally in most programming languages.

Comments

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.