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

MongoDB按月份聚合时month字段返回null的原因排查

问题

我的数据模型中包含date字段,定义如下:

date: {
    type: Date,
    default: Date.now,
},

我通过年、月、日单独字段创建Date对象存入数据库:

...
    date: new Date(year, Number(month) - 1, date),
...

在MongoDB Compass中该字段显示为:

"date": {
    "$date": {
      "$numberLong": "1670011200000"
    }
  },

我尝试对集合数据按月份进行聚合操作:

db.collection.aggregate([
  {
    $group: {
      ...
    },
    
  },
  {
    $project: {
      month: {
        $month: {
          $toDate: "$date"
        }
      },
    }
  }
])

但返回结果中month字段为null:

{
    "_id": ObjectId("6302338f4d8104216b0e889a"),
    "month": null
  },

请问为何date字段转换后获取的month会返回null?

原因及解决方法

你的date字段在MongoDB中已经是标准的Date类型(Compass显示的$date格式就是MongoDB存储Date类型的标识),但你在聚合操作中多做了一步$toDate转换——这个操作是用来将字符串、数字等非Date类型的值转为Date类型的,用它去转换已经是Date类型的字段会导致转换失败,返回null,最终$month处理null自然也返回null。

解决方法很简单,直接去掉$toDate,让$month直接处理date字段即可:

db.collection.aggregate([
  {
    $group: {
      ...
    },
    
  },
  {
    $project: {
      month: { $month: "$date" }
    }
  }
])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 10:24:09