Getting timestamp from mongodb id

JavascriptMongodb

Javascript Problem Overview


How do I get the timestamp from the MongoDB id?

Javascript Solutions


Solution 1 - Javascript

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 )

Solution 2 - Javascript

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.

Solution 3 - Javascript

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.

Solution 4 - Javascript

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

Solution 5 - Javascript

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);
};

Solution 6 - Javascript

From the official documentation:

ObjectId('mongodbIdGoesHere').getTimestamp();

Solution 7 - Javascript

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

Solution 8 - Javascript

Use $convert method like:

db.Items.find({}, { creationTime: {"$convert":{"input":"$_id", "to":"date"}}});

Solution 9 - Javascript

Find on mongoDB

db.books.find({}).limit(10).map(function (v) {
 let data = v
 data.my_date = v._id.getTimestamp()
 return data
})

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHarryView Question on Stackoverflow
Solution 1 - JavascriptKoljaView Answer on Stackoverflow
Solution 2 - JavascriptChris LynchView Answer on Stackoverflow
Solution 3 - JavascriptEric LeschinskiView Answer on Stackoverflow
Solution 4 - JavascriptwebmasterView Answer on Stackoverflow
Solution 5 - Javascriptpoke19962008View Answer on Stackoverflow
Solution 6 - JavascriptAlok DeshwalView Answer on Stackoverflow
Solution 7 - JavascriptKorbenDallasView Answer on Stackoverflow
Solution 8 - JavascriptMohammed OsmanView Answer on Stackoverflow
Solution 9 - JavascriptInfomasterView Answer on Stackoverflow