MongoDB 聚合 $sum 两个时间字段相减大于一天加一:详细教程和代码示例
"使用 MongoDB 的聚合管道中的 $dateToString 运算符将时间字段转换为 yyyy-mm-dd 格式的字符串,然后使用 $subtract 运算符计算两个日期之间的差值,最后使用 $cond 运算符判断差值是否大于1,如果是,则加1,否则加0。\n\n以下是一个示例聚合查询的代码:\n\njavascript\ndb.collection.aggregate([\n {\n $project: {\n date1: { $dateToString: { format: \"%Y-%m-%d\", date: \"$date1\" } },\n date2: { $dateToString: { format: \"%Y-%m-%d\", date: \"$date2\" } }\n }\n },\n {\n $project: {\n diff: {\n $subtract: [\n { $toDate: \"$date1\" },\n { $toDate: \"$date2\" }\n ]\n }\n }\n },\n {\n $project: {\n result: {\n $cond: {\n if: { $gt: [{ $divide: [\"$diff\", 1000 * 60 * 60 * 24] }, 1] },\n then: { $add: [1, 0] },\n else: { $add: [0, 0] }\n }\n }\n }\n }\n])\n\n\n请将 collection 替换为你的集合名称,date1 和 date2 替换为你的时间字段名称。\n\n这个聚合查询首先使用 $dateToString 运算符将时间字段转换为 yyyy-mm-dd 格式的字符串,然后使用 $subtract 运算符计算两个日期之间的差值(单位为毫秒)。接下来,使用 $divide 运算符将差值转换为天数,并使用 $gt 运算符判断差值是否大于1。最后,使用 $cond 运算符根据判断结果选择加1或加0。\n\n注意:在实际使用中,可能需要根据具体的业务需求进行适当的调整。\n
原文地址: https://www.cveoy.top/t/topic/pxHg 著作权归作者所有。请勿转载和采集!