Reputation: 54939
How do I get the timestamp from the MongoDB id?
Upvotes: 81
Views: 72636
Reputation: 4226
Use $convert
method like:
db.Items.find({}, { creationTime: {"$convert":{"input":"$_id", "to":"date"}}});
Upvotes: 3
Reputation: 1126
From the official documentation:
ObjectId('mongodbIdGoesHere').getTimestamp();
Upvotes: 2
Reputation: 873
Find on mongoDB
db.books.find({}).limit(10).map(function (v) {
let data = v
data.my_date = v._id.getTimestamp()
return data
})
Upvotes: 0
Reputation: 1044
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
Upvotes: 3
Reputation: 153822
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.
Upvotes: 43
Reputation: 723
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);
};
Upvotes: 5
Reputation: 2020
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');
}
Upvotes: 7
Reputation: 809
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.
Upvotes: 71
Reputation: 2749
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 )
Upvotes: 144