MongoDB聚合操作:如何从年月日字段生成ISODate类型字段
解决MongoDB聚合中将年月日字段转为ISODate的问题
你之前的写法失败的原因是:在聚合管道里直接调用new Date("$year", "$month", "$day")属于客户端JavaScript代码,这里的"$year"只是普通字符串,并非文档里的字段值,所以无法正确生成目标日期。
下面提供两种可行的解决方案:
方案一:使用$dateFromParts(推荐,MongoDB 3.6+)
$dateFromParts是MongoDB专门用来从年、月、日等组件生成日期的运算符,操作简单且无需处理字符串补零:
db.getCollection('Worker').aggregate([ // 生成date字段 { $addFields: { date: { $dateFromParts: { year: "$year", month: "$month", day: "$day" } } } }, // 可选:移除原来的年月日字段,只保留date { $project: { day: 0, month: 0, year: 0 } } ])
方案二:字符串拼接转日期(兼容旧版本MongoDB)
如果你的MongoDB版本低于3.6,可以先拼接标准格式的日期字符串,再转为ISODate:
db.getCollection('Worker').aggregate([ // 拼接YYYY-MM-DD格式的字符串(处理单数字月日的补零) { $addFields: { dateStr: { $concat: [ { $toString: "$year" }, "-", { $toString: { $cond: [{ $lt: ["$month", 10] }, { $concat: ["0", { $toString: "$month" }] }, { $toString: "$month" }] } }, "-", { $toString: { $cond: [{ $lt: ["$day", 10] }, { $concat: ["0", { $toString: "$day" }] }, { $toString: "$day" }] } } ] } } }, // 将字符串转为ISODate { $addFields: { date: { $toDate: "$dateStr" } } }, // 移除中间字段和原年月日字段 { $project: { day: 0, month: 0, year: 0, dateStr: 0 } } ])
内容的提问来源于stack exchange,提问作者vdev
相关产品推荐
相关产品推荐

