如何将BSON::Timestamp与Ruby Time互相转换及MongoDB查询过滤
1. 从BSON::Timestamp类中提取时间
BSON::Timestamp 原生提供了seconds实例属性直接返回Unix时间秒数,无需通过as_json转换,示例代码如下:
# 获取时间戳实例 ts = input["dateCreated"] # 直接读取秒数,转换为Ruby Time对象 create_time = Time.at(ts.seconds) # 如果你要使用as_json返回的结构处理也可以,其中t字段对应秒数 ts_json = ts.as_json create_time = Time.at(ts_json["$timestamp"]["t"])
如果需要获取增量值,同理调用ts.increment即可直接读取。
2. MongoDB Ruby驱动用时间戳进行find过滤
查询时直接构造BSON::Timestamp实例作为查询条件即可,示例代码如下:
require "bson" # 示例:查询dateCreated大于2024-01-01 00:00:00的记录 target_time = Time.parse("2024-01-01 00:00:00") # 转换为Unix秒数 target_sec = target_time.to_i # 构造BSON::Timestamp,参数依次为秒数、增量值,仅按时间维度过滤时增量传0即可 filter_ts = BSON::Timestamp.new(target_sec, 0) # 执行查询 records = your_collection.find({ "dateCreated" => { "$gte" => filter_ts } }) # 若要精确匹配已知的时间戳,同时传入对应秒数和增量即可 exact_ts = BSON::Timestamp.new(229, 3745289216) exact_record = your_collection.find({ "dateCreated" => exact_ts }).first
补充说明:MongoDB的Timestamp类型是设计用于内部oplog场景的特殊类型,如果是业务层存储业务时间,更推荐直接使用UTC Date类型,查询和处理的适配性更高。
内容的提问来源于stack exchange,提问作者user3636388
相关产品推荐
相关产品推荐

