从mongodb id获取时间戳

时间:2011-06-23 09:34:21

标签: javascript mongodb

如何从MongoDB id获取时间戳?

8 个答案:

答案 0 :(得分:96)

时间戳包含在mongoDB id的前4个字节中(参见:http://www.mongodb.org/display/DOCS/Object+IDs)。

所以你的时间戳是:

timestamp = _id.toString().substring(0,8)

date = new Date( parseInt( timestamp, 16 ) * 1000 )

答案 1 :(得分:57)

从Mongo 2.2开始,这已经发生了变化(参见:http://docs.mongodb.org/manual/core/object-id/

你可以在mongo shell中一步完成这一切:

document._id.getTimestamp();

这将返回Date对象。

答案 2 :(得分:23)

从mongoDB集合项获取时间戳,并使用演练:

时间戳深埋在mongodb物体的内部。跟着走,保持冷淡。

登录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

通过插入项目

创建数据库
> db.penguins.insert({"penguin": "skipper"})
> db.penguins.insert({"penguin": "kowalski"})
> 

检查它是否存在:

> show dbs
local      0.078125GB
penguins   0.203125GB

让这个数据库成为我们现在的数据库

> use penguins
switched to db penguins

让自己成为一个ISODate:

> ISODate("2013-03-01")
ISODate("2013-03-01T00:00:00Z")

打印一些json:

> printjson({"foo":"bar"})
{ "foo" : "bar" }

获取行:

> db.penguins.find()
{ "_id" : ObjectId("5498da1bf83a61f58ef6c6d5"), "penguin" : "skipper" }
{ "_id" : ObjectId("5498da28f83a61f58ef6c6d6"), "penguin" : "kowalski" }

我们只想检查一行

> db.penguins.findOne()
{ "_id" : ObjectId("5498da1bf83a61f58ef6c6d5"), "penguin" : "skipper" }

获取该行的_id:

> db.penguins.findOne()._id
ObjectId("5498da1bf83a61f58ef6c6d5")

从_id对象获取时间戳:

> db.penguins.findOne()._id.getTimestamp()
ISODate("2014-12-23T02:57:31Z")

获取上次添加记录的时间戳:

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

示例循环,打印字符串:

> db.penguins.find().forEach(function (doc){ print("hi") })
hi
hi

示例循环,与find()相同,打印行

> db.penguins.find().forEach(function (doc){ printjson(doc) })
{ "_id" : ObjectId("5498dbc9f83a61f58ef6c6d7"), "penguin" : "skipper" }
{ "_id" : ObjectId("5498dbd5f83a61f58ef6c6d8"), "penguin" : "kowalski" }

循环,获取系统日期:

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

循环,获取每行的日期:

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

过滤至日期

> 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")

仅针对字符串进一步过滤:

> 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(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")

将日期实例转换为yyyy-MM-dd

> print(d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate())
2014-1-1

为每行获取yyyy-MM-dd格式:

> db.penguins.find().forEach(function (doc){ d = doc._id.getTimestamp(); print(d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate()) })
2014-12-23
2014-12-23

toLocaleDateString更简洁:

> db.penguins.find().forEach(function (doc){ d = doc._id.getTimestamp(); print(d.toLocaleDateString()) })
Tuesday, December 23, 2014
Tuesday, December 23, 2014

以yyyy-MM-dd获取每一行HH:mm:ss格式:

> 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

获取最后添加的行的日期:

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

完成后删除数据库:

> use penguins
switched to db penguins
> db.dropDatabase()
{ "dropped" : "penguins", "ok" : 1 }

确保它已消失:

> show dbs
local   0.078125GB
test    (empty)

现在你的MongoDB是webscale。

答案 3 :(得分:4)

这是一个快速的PHP函数给你们所有人;)

public static function makeDate($mongoId) {

    $timestamp = intval(substr($mongoId, 0, 8), 16);

    $datum = (new DateTime())->setTimestamp($timestamp);

    return $datum->format('d/m/Y');
}

答案 4 :(得分:1)

在MongoDB ObjectId的服务器端 make _id

date = new Date( parseInt( _id.toString().substring(0,8), 16 ) * 1000 )

客户端上使用

var dateFromObjectId = function (objectId) {
return new Date(parseInt(objectId.substring(0, 8), 16) * 1000);
};

答案 5 :(得分:1)

如果您需要在GoLang中从MongoID获取时间戳:

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
}

游乐场:https://play.golang.org/p/lB9xSCmsP8I

答案 6 :(得分:0)

摘自官方文档:

ObjectId('mongodbIdGoesHere').getTimestamp();

答案 7 :(得分:0)

在mongoDB上查找

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