【问题标题】:Convert Field With Unix TimeStamp to Date (Mongodb/NodeJS)将带有 Unix 时间戳的字段转换为日期 (Mongodb/NodeJS)
【发布时间】:2020-11-30 13:29:57
【问题描述】:

我在 MongoDB 中使用聚合按 $year、$month 和 $dayOfMonth 对字段进行分组。

Transaction.aggregate(
        [{
            $group: {
                _id: {
                    year : { $year : "$createdAt" },
                    month : { $month :  "$createdAt" },
                    day : { $dayOfMonth :  "$createdAt" },
                },
                totalQuantity: {
                    $sum: "$totalQuantity"
                },
                totalAmount: {
                    $sum: "$totalAmount"
                },
                totalPayment: {
                    $sum: "$totalPayment"
                },
                count: { $sum: 1 }
            }
        }
            ]).then( res =>  console.log(res));

在上面的代码中,我使用了默认的 $createdAt 字段,但是当我尝试使用具有 Unix 时间戳的日期的 $date 时,它​​会引发错误。

我尝试了什么?

Transaction.aggregate(
        [{
            $group: {
                _id: {
                    year : { $year : new Date("$date") },
                    month : { $month :  new Date("$date") },
                    day : { $dayOfMonth :  new Date("$date") },
                },
                totalQuantity: {
                    $sum: "$totalQuantity"
                },
                totalAmount: {
                    $sum: "$totalAmount"
                },
                totalPayment: {
                    $sum: "$totalPayment"
                },
                count: { $sum: 1 }
            }
        }
            ]).then( res =>  console.log(res));

但这不起作用,因为 "$date" 作为字符串传递给 Date 构造函数。有什么解决方法吗?

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    您可以使用$toDate 来实现,将 unix 时间戳毫秒转换为 iso 日期,

    • $addFields 转换 createdAt 并替换值
      {
        $addFields: {
          createdAt: { $toDate: "$createdAt" }
        }
      },
    
    • 可以直接在$group使用
      {
        $group: {
          _id: {
            year: { $year: "$createdAt" },
            month: { $month: "$createdAt" },
            day: { $dayOfMonth: "$createdAt" }
          }
        }
      }
    

    游乐场:https://mongoplayground.net/p/-gWq0YLtLSX

    您也可以在$group 内进行转换,但这将转换三次,您可以添加一次并像上面的示例一样在组中使用。

      year: { $year: { $toDate: "$createdAt" } },
      month: { $month: { $toDate: "$createdAt" } },
      day: { $dayOfMonth: { $toDate: "$createdAt" } }
    

    【讨论】:

      猜你喜欢
      • 2019-09-15
      • 2020-10-19
      • 1970-01-01
      • 2020-12-23
      • 2016-04-24
      • 2012-07-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多