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

如何通过MongoDB $currentDate将字段更新为当日0点日期时间?

关于MongoDB $currentDate设置当日0点日期的问题

不能仅通过$currentDate实现你要的效果。$currentDate操作符的核心作用就是生成包含当前精确时间(时分秒)的Date对象,不管是使用{reportingDate: true}还是{reportingDate: {$type: "date"}}的写法,都会保留当前的时分秒信息,无法直接将时间部分置为00:00:00。

你可以通过聚合管道式更新(MongoDB 4.2及以上版本支持)来实现需求,以下是两种可行方案:

方案一:使用$dateTrunc截断日期

db.my_collection.updateMany(
  { _id: {$in: ["123", "345"]} },
  [
    { $set: {
      reportingDate: { $dateTrunc: { date: "$$NOW", unit: "day" } }
    }}
  ]
)

$$NOW代表当前系统时间,$dateTrunc按"day"单位截断后,会自动将时分秒、毫秒部分置为0,得到当日的起始时间。

方案二:用$dateFromParts构造当日日期

db.my_collection.updateMany(
  { _id: {$in: ["123", "345"]} },
  [
    { $set: {
      reportingDate: {
        $dateFromParts: {
          year: { $year: "$$NOW" },
          month: { $month: "$$NOW" },
          day: { $dayOfMonth: "$$NOW" }
        }
      }
    }}
  ]
)

通过$year、$month、$dayOfMonth从$$NOW中提取当前的年、月、日,再用$dateFromParts构造出时间部分为0的Date对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 00:07:23