如何从Spring Data MongoDB中的MongoDB ObjectId中提取时间戳? [英] How do you extract a timestamp from a MongoDB ObjectId in Spring Data MongoDB?
问题描述
MongoDB 文档建议从ObjectId中提取插入时间,而不要使用单独的时间字段.有谁知道如何使用Spring Data MongoDB做到这一点?
The MongoDB documentation recommends extracting insertion times from the ObjectId rather than having a separate time field. Does anyone know how to do this with Spring Data MongoDB?
特别是,我想查询在特定日期范围内插入的文档.
In particular, I'd like to query for documents inserted in a specific date range.
推荐答案
从ObjectId
获取时间很容易...但是您没有得到ms精度.
It's easy to get times from an ObjectId
... however you do NOT get ms precision.
org.bson.types.ObjectId
有两种可以使用的方法:getTimeSecond()
和getTime()
(与`getTimeSecond() * 1000L
相同).这些将为您提供一个unix时间戳.
org.bson.types.ObjectId
has 2 methods you can use on it: getTimeSecond()
and getTime()
(same as `getTimeSecond() * 1000L
). These will get your a unix timestamp.
我还没有将MongoDB与Spring一起使用-但是,如果您可以使用实际的ObjectId
实例,就像调用上述方法之一一样简单.
I haven't used MongoDB with Spring - but if you can get your hands on the actual ObjectId
instance its as simple as calling a one of the methods above.
现在-要查询某个时间范围内的文档,您必须倒退并根据时间戳创建ObjectId
对象.再次-这很简单-ObjectId
具有构造函数可以为您完成此操作:
Now - to query for documents in a time range you have to go backwards and create ObjectId
objects based on a timestamp. Again - this is simple - the ObjectId
has a constructor can do this for you:
ObjectId(Date time)
因此-创建2个ObjectId
实例来代表您的最小和最大时间范围,然后执行以下查询:
So - create 2 ObjectId
instances that represent your min and max time bounds then do a query like:
db.collection.find({ "field" : { $gt: value1, $lt: value2 } } );
其中value1
和value2
表示您通过ObjectId(Date time)
这篇关于如何从Spring Data MongoDB中的MongoDB ObjectId中提取时间戳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!