Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose aggregation groupby on day,week,year [duplicate]

I am using nodejs and mongodb for database

My document is:

{
    "_id": "58466d6a0b3f4d2e2fa22905",
    "updatedAt": "2016-12-06T07:48:58.435Z",
    "createdAt": "2017-12-06T07:48:58.435Z",
    "userId": "56d04e265a2100c72a311334",
    "__v": 0
  }

User will give fromDate ,toDate and frequency in clientside in which frequency value can be 0,1,2 where 0 means day,1 means week,2 means year.

On basis of above data i want to generate report

for ex: if user give fromDate=2016-12-1 and toDate=2016-12-6.

if frequency is 0 the result would be

{
  2016-12-01:{
    count:1
          }
  2016-12-02:{
      count:7   
        }
  2016-12-06:{
      count:8
      }
  }

if frequency is 1 the result would be

{
  2016-12-01 to 2016-12-06:{
    count:16
          }
  }

if frequency is 2 the result would be

{
  2016:{
    count:16
          }
  }

In which count is number of documents

I have done like this:

var aggregate = [{
        $match: {
            createdAt: {
                $gte: fromDate,
                $lt: toDate
            }
        }
    }, {
        $group: {
            // what should i will do here
            },
            count: {
                $sum: 1
            }
        }
    }]

    return LoginReportModel.aggregate(aggregate).exec();

OR Any one know other better approach like using lodash also welcome

Edited: I also want count of documents to be unique on userId

like image 537
Simran Avatar asked Nov 23 '25 16:11

Simran


1 Answers

Check out the documentation on $dateToString

You could do it like this:

var frequency = 2

var frequencyDateFormatMap = {
  0: '%Y-%m-%d',
  1: '%U',
  2: '%Y'
}

var frequencyDateFormat = frequencyDateFormatMap[frequency]

var aggregate = [
  {$match: {
    createdAt: {
      $gte: fromDate,
      $lt: toDate
    }
  }},
  {$project: {
    frequency: {
      $dateToString: {
        format: frequencyDateFormat,
        date: '$createdAt'
      }
    }
  }},
  {$group: {
    _id: '$frequency',
    count: {
      $sum: 1
    }
  }}
]

return LoginReportModel.aggregate(aggregate).exec()
like image 51
Rudi Avatar answered Nov 26 '25 08:11

Rudi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!