Reputation: 3281
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
Upvotes: 2
Views: 11710
Reputation: 49729
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.
Upvotes: 2
Reputation: 60692
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.
Upvotes: 2