简体   繁体   English

MongoDB NodeJS - 如何获得两个日期之间的值总和?

[英]MongoDB NodeJS - How to get sum of values between two dates?

I have the below code snippet which will retrieve Date and count from a MongoDb collection from a specific date.我有下面的代码片段,它将从特定日期的 MongoDb 集合中检索日期和计数。 Example: Retrieve date, count from 05-05-2020.示例:检索日期,从 05-05-2020 开始计数。

||Date||Count|| ||日期||计数|| |05-06-2020|4| |05-06-2020|4| |05-07-2020|25| |05-07-2020|25| and so on.等等。

i want to add another logic to retrieve aggregate sum of 7 days instead of individual dates.我想添加另一个逻辑来检索 7 天的总和而不是单个日期。 Appreciate any help.感谢任何帮助。

    mongoClient.db().collection(COLLECTION.AUDIT).aggregate([
        {
            $match: { created_at: { $gt: date } }
        },
        {
            $group: {
                _id: {
                    $dateToString: { format: "%Y-%m-%d", date: "$created_at" }
                },
                count: { $sum: 1 }
            }
        },
        {
            $sort: { "_id": -1 }
        }
    ])

The simplest way to do what I think you're asking would be to transform your group operator to $week instead of $dateToString.做我认为您所要求的最简单的方法是将您的组运算符转换为 $week 而不是 $dateToString。 Since a week is 7 days, this will group all the documents from the same week, and return a count of the documents, along with the number of the week.由于一周是 7 天,这将对同一周的所有文档进行分组,并返回文档的计数以及周数。 To get both results from 1 query, combine them into a facet.要从 1 个查询中获取两个结果,请将它们组合成一个构面。 So:所以:

mongoClient.db().collection(COLLECTION.AUDIT).aggregate([
    {
        $match: { created_at: { $gt: date } }
    },
    {
        $facet: {
            by_week: {
                $group: {
                    _id: { $week: $created_at},
                    count: { $sum: 1 }
                },
                { $sort: { "_id": -1 }}
            }, 
            by_day:  {
                        $group: {
                            _id: {
                                $dateToString: { format: "%Y-%m-%d", date: "$created_at" }
                            },
                            count: { $sum: 1 }
                        }
                    },
                    {  $sort: { "_id": -1 }}  
                }
    },
  
])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM