簡體   English   中英

將帶有 Unix 時間戳的字段轉換為日期(Mongodb/NodeJS)

[英]Convert Field With Unix TimeStamp to Date (Mongodb/NodeJS)

我在 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 構造函數。 有什么解決方法嗎?

您可以使用$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" } }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM