【问题标题】:Getting timestamp from mongodb id从 mongodb id 获取时间戳
【发布时间】:2011-09-21 01:48:35
【问题描述】:

如何从 MongoDB id 中获取时间戳?

【问题讨论】:

  • 仅供参考,第二个答案可能应该是公认的答案。它在使用本机 MongoDB JS 驱动程序的任何 JS 驱动程序中实现(这是我所知道的全部)。
  • 我不同意 Dropped.on.Caprica,接受的答案不需要你有任何图书馆来获取日期,所以对我来说更好
  • 在我的情况下,我必须在客户端进行时间戳解析,而不是 MongoDB 的 JS 驱动程序所在的位置,所以对我来说,目前接受的答案也是最好的答案。但也很高兴知道 * getTimestamp,所以对两者都 +1 :)

标签: javascript mongodb


【解决方案1】:

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

所以你的时间戳是:

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

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

【讨论】:

    【解决方案2】:

    从 Mongo 2.2 开始,这种情况发生了变化(请参阅:http://docs.mongodb.org/manual/core/object-id/

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

    document._id.getTimestamp();
    

    这将返回一个 Date 对象。

    【讨论】:

    • 还有python:document_id.generation_time
    • 和 PHP $doc['_id']->getTimestamp();
    • 这不是重点,因为 OP 没有指定环境。在没有任何库且仅有可用的十六进制字符串的普通 JS 前端环境中,Kolja 的回答更有帮助。两个答案都很好。
    【解决方案3】:

    通过演练从 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 是网络规模的。

    【讨论】:

    • 虽然可能很有趣,但这个答案中唯一解决这个问题的部分是“从 _id 对象获取时间戳”......
    • 谢谢! forEach 是我正在寻找来操作来自 find 函数的结果文档
    【解决方案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');
    }
    

    【讨论】:

    • 我如何在 Spring Boot 中做到这一点
    【解决方案5】:

    服务器端制作MongoDB ObjectId的_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);
    };
    

    【讨论】:

      【解决方案6】:

      来自the official documentation

      ObjectId('mongodbIdGoesHere').getTimestamp();
      

      【讨论】:

      • 我如何在 Spring Boot DTO 类中做到这一点
      • 如果对您有用,请检查此链接Click Here
      【解决方案7】:

      如果您需要在 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

      【讨论】:

        【解决方案8】:

        使用$convert 方法如:

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

        【讨论】:

          【解决方案9】:

          在 mongoDB 上查找

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

          【讨论】:

            猜你喜欢
            • 2020-06-25
            • 2018-01-06
            • 1970-01-01
            • 2014-11-21
            • 1970-01-01
            • 2011-12-08
            • 2011-08-08
            • 1970-01-01
            相关资源
            最近更新 更多