shell – 如何从Mongo ObjectID中提取创建的日期

我使用Mongo shell来查询我的Mongo数据库。我想使用ObjectID中包含的时间戳作为我的查询的一部分,也作为一个列提取到输出。我已经设置Mongo自己创建ObjectIDs。

我的问题是我找不到如何使用ObjectID提取其时间戳。

这里是我想要工作的查询。 ‘createdDate’字段是一个占位符;不确定正确的字段是:

//Find everything created since 1/1/2011
db.myCollection.find({date: {$gt: new Date(2011,1,1)}});

//Find everything and return their createdDates
db.myCollection.find({},{createdDate:1});
getTimestamp()

你需要的功能是这一个,它已经包含在你已经在shell中:

ObjectId.prototype.getTimestamp = function() {
    return new Date(parseInt(this.toString().slice(0,8),16)*1000);
}

参考文献

从文档中查看此部分:

> Extract insertion times from _id rather than having a separate timestamp field

这个单元测试也演示了同样的:

> mongo / jstests / objid6.js

使用Mongo shell的示例:

> db.col.insert( { name: "Foo" } );
> var doc = db.col.findOne( { name: "Foo" } );
> var timestamp = doc._id.getTimestamp();

> print(timestamp);
Wed Sep 07 2011 18:37:37 GMT+1000 (AUS Eastern Standard Time)

> printjson(timestamp);
ISODate("2011-09-07T08:37:37Z")

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...