简体   繁体   中英

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. Example: Retrieve date, count from 05-05-2020.

||Date||Count|| |05-06-2020|4| |05-07-2020|25| and so on.

i want to add another logic to retrieve aggregate sum of 7 days instead of individual dates. 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. 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. To get both results from 1 query, combine them into a facet. 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 }}  
                }
    },
  
])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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