如何从 Spring Data MongoDB 中的 MongoDB ObjectId 中提取时间戳? [英] How do you extract a timestamp from a MongoDB ObjectId in Spring Data MongoDB?
问题描述
MongoDB documentation 建议从 ObjectId 中提取插入时间,而不是使用单独的时间字段.有谁知道如何使用 Spring Data MongoDB 做到这一点?
特别是,我想查询插入特定日期范围的文档.
从 ObjectId
中获取时间很容易...但是您无法获得毫秒精度.
org.bson.types.ObjectId
有 2 种方法可供您使用:getTimeSecond()
和 getTime()
(与`getTimeSecond() * 1000L
).这些将获得您的 unix 时间戳.
我没有将 MongoDB 与 Spring 一起使用 - 但如果你能掌握实际的 ObjectId
实例,它就像调用上述方法之一一样简单.
现在 - 要查询某个时间范围内的文档,您必须倒退并根据时间戳创建 ObjectId
对象.再一次 - 这很简单 - ObjectId
有一个构造函数可以为您执行此操作:
ObjectId(日期时间)
所以 - 创建 2 个 ObjectId
实例来代表您的最小和最大时间界限,然后执行如下查询:
db.collection.find({ "field" : { $gt: value1, $lt: value2 } } );
其中 value1
和 value2
代表您通过 ObjectId(Date time)
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.
It's easy to get times from an ObjectId
... however you do NOT get ms precision.
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.
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.
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)
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 } } );
where value1
and value2
represent the ObjectId
instance you created via ObjectId(Date time)
这篇关于如何从 Spring Data MongoDB 中的 MongoDB ObjectId 中提取时间戳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!