You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB如何从时间戳提取年份?现有方案失效求解决

解决MongoDB从秒级时间戳提取年份的问题

你的问题核心是时间戳单位不匹配:MongoDB的$toDate默认识别毫秒级时间戳,但你的createdAt是秒级的(1617308748),直接转换会得到错误日期,自然提不出正确年份。

给你两个可用的聚合查询方案:

方案1:转毫秒后提取年份

db.collection.aggregate([
  {
    $addFields: {
      year: {
        $year: { $toDate: { $multiply: ["$createdAt", 1000] } }
      }
    }
  }
])

方案2:用$dateFromParts直接处理秒级戳(MongoDB 4.0+可用)

db.collection.aggregate([
  {
    $addFields: {
      year: {
        $year: {
          $dateFromParts: {
            timestamp: "$createdAt"
          }
        }
      }
    }
  }
])

说明

  • 方案1里,$multiply把秒级时间戳乘1000转换成毫秒格式,让$toDate能识别出正确日期,再用$year提取年份。
  • 方案2的$dateFromParts支持直接传入秒级时间戳,无需手动转换单位,更简洁。

执行任意一个查询后,都会得到你期望的输出:

{
    "_id" : ObjectId("60662c4cbcd96707a8ba8fa7"),
    "createdAt" : NumberInt(1617308748),
    "email" : "abc.com",
    "score" : NumberInt(50),
    "year" : NumberInt(2021)
}

内容的提问来源于stack exchange,提问作者Vishal Tyagi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 03:47:16