当您将 UNIX 时间存储为时间戳时,如何按月对过去 12 个月的文档进行分组?

发布于 2025-01-13 01:07:35 字数 1301 浏览 0 评论 0原文

我有一个集合,其中数据每天根据 UNIX 纪元时间更新。例如:

{ 
    "uID" : "12345678", 
    "midNightTimeStamp" : NumberInt(1645381800), // 21st Feb 2022 midnight IST
    "energyConsumed" : NumberInt(53)
},
{ 
    "uID" : "12345678", 
    "midNightTimeStamp" : NumberInt(1645641000), // 24th Feb 2022 midnight IST
    "energyConsumed" : NumberInt(30)
}

现在,如果您想按月查询过去 12 个月的数据,您会采取什么方法来解决这个问题?我所知道的是,我可以将我的数据分组到聚合查询中,如下所示:

 $project: {
            energyConsumed: 1.0,
            year: {
              $year: // How would you convert this from epoch
            },
            month: {
              $month: // How would you convert this from epoch
            }
          },

现在,如果我想将过去 12 个月的数据分组为如下所示

  $group: {
            _id: '$month',
            energyConsumed: {
              $sum: '$energyConsumed'
            }
          }

,我想要的输出将是:

{
  id: 04 // (something like 04 or just April but data should be sorted month and year wise April 2021),
  energyConsumed: 4179772
},
{
  id: 05 // (something like 05 or just May but data should be sorted month and year wise),
  energyConsumed: 6179772
},
...
...
{
  id: 03 // (something like 03 or just March (March 2022),
  energyConsumed: 5643772
}

I have a collection where data is updated daily based on unix epoch time. For example:

{ 
    "uID" : "12345678", 
    "midNightTimeStamp" : NumberInt(1645381800), // 21st Feb 2022 midnight IST
    "energyConsumed" : NumberInt(53)
},
{ 
    "uID" : "12345678", 
    "midNightTimeStamp" : NumberInt(1645641000), // 24th Feb 2022 midnight IST
    "energyConsumed" : NumberInt(30)
}

Now if you wanted to query last 12 months data month wise, what would have been your approach to solve this? All I know is that I could group my data in aggregation query something like this:

 $project: {
            energyConsumed: 1.0,
            year: {
              $year: // How would you convert this from epoch
            },
            month: {
              $month: // How would you convert this from epoch
            }
          },

Now if I wanted to group my data from last 12 months as something like this

  $group: {
            _id: '$month',
            energyConsumed: {
              $sum: '$energyConsumed'
            }
          }

And my desired output will be:

{
  id: 04 // (something like 04 or just April but data should be sorted month and year wise April 2021),
  energyConsumed: 4179772
},
{
  id: 05 // (something like 05 or just May but data should be sorted month and year wise),
  energyConsumed: 6179772
},
...
...
{
  id: 03 // (something like 03 or just March (March 2022),
  energyConsumed: 5643772
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

忆沫 2025-01-20 01:07:35

也许是这样的:

 db.collection.aggregate([
 {
   $group: {
    _id: {
      $dateToString: {
       format: "%Y-%m",
        date: {
          $toDate: {
          "$multiply": [
            "$midNightTimeStamp",
            1000
          ]
        }
      }
     }
     },
     monthlyConsumption: {
       $sum: "$energyConsumed"
     }
    }
   }
 ])

解释:

$group 基于由 midNightTimeStamp 字段提取的年月 ("YYYY-mm" ) 和 $sum 每月消耗

游乐场

Maybe this:

 db.collection.aggregate([
 {
   $group: {
    _id: {
      $dateToString: {
       format: "%Y-%m",
        date: {
          $toDate: {
          "$multiply": [
            "$midNightTimeStamp",
            1000
          ]
        }
      }
     }
     },
     monthlyConsumption: {
       $sum: "$energyConsumed"
     }
    }
   }
 ])

Explained:

$group based on Year-Month ("YYYY-mm" ) extracted by the midNightTimeStamp field and $sum the monthly consumption

playground

眼眸里的快感 2025-01-20 01:07:35

要捕获从现在开始的最后 12 个月,请将其放在上面的 $group 阶段之前:

// Back up one year from right now:                                                                           
var sdate = new ISODate();
sdate.setYear((sdate.getYear()-1) + 1900);

db.foo.aggregate([
    {$match: {$expr: {$gt:[{$toDate: {$multiply:['$midNightTimeStamp',1000]}},sdate]} } },
    {$group: { ... // as above

To catch just the last 12 months from right now, throw this in front of the $group stage above:

// Back up one year from right now:                                                                           
var sdate = new ISODate();
sdate.setYear((sdate.getYear()-1) + 1900);

db.foo.aggregate([
    {$match: {$expr: {$gt:[{$toDate: {$multiply:['$midNightTimeStamp',1000]}},sdate]} } },
    {$group: { ... // as above
岛徒 2025-01-20 01:07:35

如果您已经运行 MongoDB 5.0 版,则可以使用 $dateTrunc

db.collection.aggregate([
  {
    $group: {
      _id: {
        $dateTrunc: {
          date: { $toDate: { $toLong: { $multiply: ["$midNightTimeStamp", 1000] } } },
          unit: "month",
          timezone: "Europe/Zurich"          
        }
      },
      energyConsumed: { $sum: "$energyConsumed" }
    }
  }
])

由于 timezone 选项,它可能比 $dateToString: { format: "%Y-%m" ... 更精确。

If you run already MongoDB version 5.0 then you can use $dateTrunc:

db.collection.aggregate([
  {
    $group: {
      _id: {
        $dateTrunc: {
          date: { $toDate: { $toLong: { $multiply: ["$midNightTimeStamp", 1000] } } },
          unit: "month",
          timezone: "Europe/Zurich"          
        }
      },
      energyConsumed: { $sum: "$energyConsumed" }
    }
  }
])

It might be more precise than $dateToString: { format: "%Y-%m" ... due to timezone option.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文