如何从Spring Data MongoDB中的MongoDB ObjectId中提取时间戳? [英] How do you extract a timestamp from a MongoDB ObjectId in Spring Data MongoDB?

查看:138
本文介绍了如何从Spring Data MongoDB中的MongoDB ObjectId中提取时间戳?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 } } );

其中value1value2表示您通过ObjectId(Date time)

这篇关于如何从Spring Data MongoDB中的MongoDB ObjectId中提取时间戳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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