MongoDB日期转换FIND语句实现:字符串时间戳转标准日期方法
MongoDB 毫秒时间戳字符串转标准Date类型查询方案
你提到的1638811740593属于毫秒级Unix时间戳,要实现和SQL语句select date(1638811740593) from dummy完全等效的效果,使用MongoDB聚合管道的$toDate运算符即可实现,普通find查询的投影能力不足以完成类型转换,推荐使用以下写法:
1. 直接转换固定时间戳(匹配你给出的SQL示例)
db.dummy.aggregate([ { $project: { _id: 0, // 不返回默认_id字段,和SQL只返回转换后字段的逻辑一致 convertedDate: { $toDate: 1638811740593 } } } ])
2. 转换集合中存储的时间戳字符串字段
如果你的时间戳是以字符串格式存储在集合的某个字段中(比如字段名为create_ts_str),将常量替换为字段引用即可:
// your_collection替换为你的实际集合名 db.your_collection.aggregate([ { $project: { _id: 0, convertedDate: { $toDate: "$create_ts_str" } } } ])
注意事项
$toDate运算符兼容MongoDB 4.0及以上版本,同时支持数字类型、可转为数字的字符串类型的毫秒时间戳转换- 如果你只需要保留日期部分(去掉时分秒),可以叠加
$dateTrunc运算符:db.dummy.aggregate([ { $project: { _id: 0, dateOnly: { $dateTrunc: { date: { $toDate: 1638811740593 }, unit: "day" } } } } ]) - 如果你使用的是MongoDB 3.2及更早版本没有
$toDate运算符,可以用$add间接实现转换:convertedDate: { $add: [new Date(0), "$create_ts_str"] },本质是把时间戳叠加到JS基准时间戳上得到对应日期。
内容的提问来源于stack exchange,提问作者ravis
相关产品推荐
相关产品推荐

