如何通过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
相关产品推荐
相关产品推荐

