如何从 Mongo ObjectID 中提取创建日期 [英] How do I extract the created date out of a Mongo ObjectID

查看:10
本文介绍了如何从 Mongo ObjectID 中提取创建日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using the Mongo shell to query my Mongo db. I want to use the timestamp contained in the ObjectID as part of my query and also as a column to extract into output. I have setup Mongo to create ObjectIDs on its own.

我的问题是我不知道如何使用 ObjectID 来提取其时间戳.

My problem is I can not find out how to work with the ObjectID to extract its timestamp.

以下是我正在尝试解决的问题.createdDate"字段是占位符;不确定正确的字段是什么:

Here are the queries I am trying to get working. The 'createdDate' field is a placeholder; not sure what the correct field is:

//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中了:

getTimestamp()

The function you need is this one, it's included for you already in the shell:

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

参考文献

从文档中查看此部分:

References

Check out this section from the docs:

此单元测试也演示了相同的内容:

This unit test also demostrates the same:

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

这篇关于如何从 Mongo ObjectID 中提取创建日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆