如何从 Mongo ObjectID 中提取创建日期
我正在使用 Mongo shell 来查询我的 Mongo 数据库。我想使用 ObjectID 中包含的时间戳作为查询的一部分,并作为提取到输出中的列。我已经设置 Mongo 来自行创建 ObjectID。
我的问题是我不知道如何使用 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});
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.
My problem is I can not find out how to work with the ObjectID to extract its timestamp.
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});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
getTimestamp()
您需要的函数就是这个,它已经包含在 shell 中:
参考资料
从文档中查看此部分:
此单元测试也演示了相同的内容:
使用 Mongo shell 的示例:
getTimestamp()
The function you need is this one, it's included for you already in the shell:
References
Check out this section from the docs:
This unit test also demostrates the same:
Example using the Mongo shell:
这个问题有助于理解如何使用 _id查询情况下嵌入时间戳(参考 Mongo Extended JSON 文档)。它是这样完成的:
查找早于 oid 给出的文档创建的文档。与自然排序和限制一起使用,您可以利用 BSON _ids 创建类似 Twitter 的 API 查询(给我您最后一个 OID,我将提供另外 20 个)
This question is helpful to understand of how to use the _id's embedded timestamp in query situations (refers to the Mongo Extended JSON documentation). This is how it's done:
finds documents created earlier than the one that's given by oid. Used together with natural sorting and limiting you can utilize BSON _ids to create Twitter-like API queries (give me the last OID you have and I'll provide twenty more)
在 python 中,你可以这样做:
我认为,ObjectId.from_datetime() - 它是标准 bson lib 的一个有用方法
也许其他语言绑定有替代的内置函数。
来源: http://api.mongodb.org/python/current/api /bson/objectid.html
In python you can do this:
I think, ObjectId.from_datetime() - its a useful method of standard bson lib
Maybe other language bindings have alternative builtin function.
Source: http://api.mongodb.org/python/current/api/bson/objectid.html
要使用 ObjectId 中包含的时间戳并返回在特定日期之后创建的文档,您可以将
$where
与函数一起使用。例如,
该函数需要返回一个真值,以便该文档包含在结果中。参考: $where
Mongo日期对象可以不过看起来有点奇怪。有关构造函数的详细信息,请参阅 mongo Date() 文档。
摘抄:
To use the timestamp contained in the ObjectId and return documents created after a certain date, you can use
$where
with a function.e.g.
The function needs to return a truthy value for that document to be included in the results. Reference: $where
Mongo date objects can seem a bit peculiar though. See the mongo Date() documentation for constructor details.
excerpt: