skip to Main Content

My records like this [{ createdAt }, {createdAt}, {createdAt} ]

I need average records per month.

january => 3 records
february => 2 records etc..

2

Answers


  1. You can try to $group by month and year when counting and by month when averaging:

    db.collection.aggregate([
      {
        $group: {
          _id: {
            month: {
              $month: "$createdAt"
            },
            year: {
              $year: "$createdAt"
            },
            
          },
          count: {
            $sum: 1
          }
        }
      },
      {
        $group: {
          _id: {
            month: "$_id.month"
          },
          average: {
            $avg: "$count"
          }
        }
      },
      {
        $project: {
          _id: 0,
          month: "$_id.month",
          average: 1
        }
      }
    ])
    

    Link to playground

    Login or Signup to reply.
  2. Not fully clear what you mean by "average records per month" but I think it would be this:

    db.collection.aggregate([
       {
          $group: {
             _id: {
                $dateTrunc: {
                   date: "$createdAt",
                   unit: "month"
                }
             },
             count: { $count: {} }
          }
       },
       {
          $group: {
             _id: null,
             data: { $push: { k: { $toString: { $month: "$_id" } }, v: "$count" } }
          }
       },
       { $replaceWith: { $arrayToObject: "$data" } }
    ])
    

    Getting the month name is not so easy, either you use a external library or build your own with $switch

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search