How do I get the timestamp from the MongoDB id?
-
1Just as an FYI, the second answer should probably be the accepted answer. It's implemented in any JS driver that uses the native MongoDB JS Driver (which is all of them that I know of). – AlbertEngelB Feb 06 '14 at 20:38
-
I don't agree Dropped.on.Caprica, the accepted answer doesn't require you to have any library to get the date, so for me it's better – Louie Almeda Mar 21 '17 at 07:43
-
2I'n my case I had to do the timestamp parsing on the client side, and not where the JS driver for MongoDB resided, so for me also the currently accepted answer is the best one. But it's nice to know about the * `getTimestamp` as well, so +1 to both :) – Øyvind Bråthen Feb 20 '18 at 09:33
9 Answers
The timestamp is contained in the first 4 bytes of a mongoDB id (see: http://www.mongodb.org/display/DOCS/Object+IDs).
So your timestamp is:
timestamp = _id.toString().substring(0,8)
and
date = new Date( parseInt( timestamp, 16 ) * 1000 )

- 2,667
- 1
- 30
- 29
As of Mongo 2.2, this has changed (see: http://docs.mongodb.org/manual/core/object-id/)
You can do this all in one step inside of the mongo shell:
document._id.getTimestamp();
This will return a Date object.

- 789
- 6
- 4
-
3
-
-
This not more to the point, as OP did not specify the environment. In a plain JS frontend environment without any libraries and the mere hex string available, Kolja's answer is more helpful. Both answers are good. – phil294 Aug 20 '19 at 12:59
Get the timestamp from a mongoDB collection item, with walkthrough:
The timestamp is buried deep within the bowels of the mongodb object.
Login to mongodb shell
ubuntu@ip-10-0-1-223:~$ mongo 10.0.1.223
MongoDB shell version: 2.4.9
connecting to: 10.0.1.223/test
Create your database by inserting items
> db.penguins.insert({"penguin": "skipper"})
> db.penguins.insert({"penguin": "kowalski"})
>
Check if it is there:
> show dbs
local 0.078125GB
penguins 0.203125GB
Lets make that database the one we are on now
> use penguins
switched to db penguins
Get yourself an ISODate:
> ISODate("2013-03-01")
ISODate("2013-03-01T00:00:00Z")
Print some json:
> printjson({"foo":"bar"})
{ "foo" : "bar" }
Get the rows back:
> db.penguins.find()
{ "_id" : ObjectId("5498da1bf83a61f58ef6c6d5"), "penguin" : "skipper" }
{ "_id" : ObjectId("5498da28f83a61f58ef6c6d6"), "penguin" : "kowalski" }
We only want to inspect one row
> db.penguins.findOne()
{ "_id" : ObjectId("5498da1bf83a61f58ef6c6d5"), "penguin" : "skipper" }
Get the _id of that row:
> db.penguins.findOne()._id
ObjectId("5498da1bf83a61f58ef6c6d5")
Get the timestamp from the _id object:
> db.penguins.findOne()._id.getTimestamp()
ISODate("2014-12-23T02:57:31Z")
Get the timestamp of the last added record:
> db.penguins.find().sort({_id:-1}).limit(1).forEach(function (doc){ print(doc._id.getTimestamp()) })
Tue Dec 23 2014 03:04:53 GMT+0000 (UTC)
Example loop, print strings:
> db.penguins.find().forEach(function (doc){ print("hi") })
hi
hi
Example loop, same as find(), print the rows
> db.penguins.find().forEach(function (doc){ printjson(doc) })
{ "_id" : ObjectId("5498dbc9f83a61f58ef6c6d7"), "penguin" : "skipper" }
{ "_id" : ObjectId("5498dbd5f83a61f58ef6c6d8"), "penguin" : "kowalski" }
Loop, get the system date:
> db.penguins.find().forEach(function (doc){ doc["timestamp_field"] = new Date(); printjson(doc); })
{
"_id" : ObjectId("5498dbc9f83a61f58ef6c6d7"),
"penguin" : "skipper",
"timestamp_field" : ISODate("2014-12-23T03:15:56.257Z")
}
{
"_id" : ObjectId("5498dbd5f83a61f58ef6c6d8"),
"penguin" : "kowalski",
"timestamp_field" : ISODate("2014-12-23T03:15:56.258Z")
}
Loop, get the date of each row:
> db.penguins.find().forEach(function (doc){ doc["timestamp_field"] = doc._id.getTimestamp(); printjson(doc); })
{
"_id" : ObjectId("5498dbc9f83a61f58ef6c6d7"),
"penguin" : "skipper",
"timestamp_field" : ISODate("2014-12-23T03:04:41Z")
}
{
"_id" : ObjectId("5498dbd5f83a61f58ef6c6d8"),
"penguin" : "kowalski",
"timestamp_field" : ISODate("2014-12-23T03:04:53Z")
}
Filter down to just the dates
> db.penguins.find().forEach(function (doc){ doc["timestamp_field"] = doc._id.getTimestamp(); printjson(doc["timestamp_field"]); })
ISODate("2014-12-23T03:04:41Z")
ISODate("2014-12-23T03:04:53Z")
Filterdown further for just the strings:
> db.penguins.find().forEach(function (doc){ doc["timestamp_field"] = doc._id.getTimestamp(); print(doc["timestamp_field"]) })
Tue Dec 23 2014 03:04:41 GMT+0000 (UTC)
Tue Dec 23 2014 03:04:53 GMT+0000 (UTC)
Print a bare date, get its type, assign a date:
> print(new Date())
Tue Dec 23 2014 03:30:49 GMT+0000 (UTC)
> typeof new Date()
object
> new Date("11/21/2012");
ISODate("2012-11-21T00:00:00Z")
Convert instance of date to yyyy-MM-dd
> print(d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate())
2014-1-1
get it in yyyy-MM-dd format for each row:
> db.penguins.find().forEach(function (doc){ d = doc._id.getTimestamp(); print(d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate()) })
2014-12-23
2014-12-23
the toLocaleDateString is briefer:
> db.penguins.find().forEach(function (doc){ d = doc._id.getTimestamp(); print(d.toLocaleDateString()) })
Tuesday, December 23, 2014
Tuesday, December 23, 2014
Get each row in yyyy-MM-dd HH:mm:ss format:
> db.penguins.find().forEach(function (doc){ d = doc._id.getTimestamp(); print(d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds()) })
2014-12-23 3:4:41
2014-12-23 3:4:53
Get the date of the last added row:
> db.penguins.find().sort({_id:-1}).limit(1).forEach(function (doc){ print(doc._id.getTimestamp()) })
Tue Dec 23 2014 03:04:53 GMT+0000 (UTC)
Drop the database when you are done:
> use penguins
switched to db penguins
> db.dropDatabase()
{ "dropped" : "penguins", "ok" : 1 }
Make sure it's gone:
> show dbs
local 0.078125GB
test (empty)
Now your MongoDB is webscale.

- 20,799
- 66
- 75
- 101

- 146,994
- 96
- 417
- 335
-
11While perhaps interesting, the only part of this answer that addresses the question is "Get the timestamp from the _id object"... – ZachB Jan 26 '16 at 21:07
-
thank you! `forEach` is what I'm looking for to manipulate the resulting docs from the `find` function – asgs Jan 19 '22 at 14:49
Here is a quick php function for you all ;)
public static function makeDate($mongoId) {
$timestamp = intval(substr($mongoId, 0, 8), 16);
$datum = (new DateTime())->setTimestamp($timestamp);
return $datum->format('d/m/Y');
}

- 1,960
- 24
- 29
In the server side make _id
of MongoDB ObjectId
date = new Date( parseInt( _id.toString().substring(0,8), 16 ) * 1000 )
And on the client side use
var dateFromObjectId = function (objectId) {
return new Date(parseInt(objectId.substring(0, 8), 16) * 1000);
};

- 714
- 1
- 9
- 13
If you need to get timestamp from MongoID in a GoLang:
package main
import (
"fmt"
"github.com/pkg/errors"
"strconv"
)
const (
mongoIDLength = 24
)
var ErrInvalidMongoID = errors.New("invalid mongoID provided")
func main() {
s, err := ExtractTimestampFromMongoID("5eea13924a04cb4b58fe31e3")
if err != nil {
fmt.Print(err)
return
}
fmt.Printf("%T, %v\n", s, s)
// convert to usual int
usualInt := int(s)
fmt.Printf("%T, %v\n", usualInt, usualInt)
}
func ExtractTimestampFromMongoID(mongoID string) (int64, error) {
if len(mongoID) != mongoIDLength {
return 0, errors.WithStack(ErrInvalidMongoID)
}
s, err := strconv.ParseInt(mongoID[0:8], 16, 0)
if err != nil {
return 0, err
}
return s, nil
}
Playground: https://play.golang.org/p/lB9xSCmsP8I

- 944
- 9
- 16
Use $convert
method like:
db.Items.find({}, { creationTime: {"$convert":{"input":"$_id", "to":"date"}}});

- 3,688
- 2
- 27
- 25
From the official documentation:
ObjectId('mongodbIdGoesHere').getTimestamp();

- 239,200
- 50
- 490
- 574

- 1,128
- 9
- 20
-
-
Please check this link if works for you [Click Here](https://www.codota.com/code/java/methods/org.bson.types.ObjectId/getTimestamp) – Alok Deshwal Jul 06 '21 at 10:43
Find on mongoDB
db.books.find({}).limit(10).map(function (v) {
let data = v
data.my_date = v._id.getTimestamp()
return data
})

- 793
- 7
- 8