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

查看:117
本文介绍了如何从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()

您需要的功能是这一功能,它已包含在外壳中:

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天全站免登陆