且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 MongoDB 聚合和 NodeJS 中计算过去 200 天的平均值

更新时间:2023-11-14 14:31:46

在对文档进行分组之前,您必须对其进行过滤.应该是这样的:

You have to filter documents before you group them. Should be like this:

db.collection.aggregate([
   {
      $addFields: {
         DateObj: {
            $regexFindAll: { input: "$Date", regex: "\\d+" }
         }
      }
   },
   {
      $set: {
         DateObj: {
            $dateFromParts: {
               year: { $toInt: { $arrayElemAt: ["$DateObj.match", 0] } },
               month: { $toInt: { $arrayElemAt: ["$DateObj.match", 1] } },
               day: { $toInt: { $arrayElemAt: ["$DateObj.match", 2] } },
               hour: { $toInt: { $arrayElemAt: ["$DateObj.match", 3] } },
               minute: { $toInt: { $arrayElemAt: ["$DateObj.match", 4] } },
               second: { $toInt: { $arrayElemAt: ["$DateObj.match", 5] } },
               timezone: "Europe/Zurich"
            }
         }
      }
   },
   {
      $match: {
         $expr: {
            $gte: ["$DateObj", { $subtract: ["$$NOW", 200 * 60 * 60 * 24 * 1000] }]
         }
      }
   },
   {
      "$group": {
         _id: null,
         "Volume": {
            "$avg": "$Volume"
         }
      }
   }
])