mongodb

Unknown group operator '$month' error in MongoDB


I have SERVICES collection with such structure:

{
 {
    "_id" : NumberInt(2),
    "ServiceNM" : "Electrical",
    "Pay" : [
        {
            "_id" : NumberInt(1),
            "PaySum" : 658.7,
            "PayDate" : ISODate("2022-02-07T21:00:00.000+0000"),
            "PayMonth" : NumberInt(12),
            "PayYear" : NumberInt(2025)
        },
      ...
    ]
 }
 ...
}

I am trying to get sums of pay for every service by month with this query:

db.runCommand({ "aggregate": "SERVICES", pipeline: [
    { $project: {
        Pay: 1
    }},
    { $unwind: "$Pay" },
    { $group: {
        _id: "$_id",
        month: {$month: "$Pay.PayDate"},
        sum: {$sum: "$Pay.PaySum"}
    }}    
    ], cursor: {}})

but I have unknown group operator '$month' error


Solution

  • Try this if you want to group by service _idand month (I'm assuming that you can use PayMonth as PayDate, so you don't need to extract month from the full date).

    db.services.aggregate([
      {
        $project: {
          _id: 1,
          Pay: 1
        }
      },
      {
        $unwind: "$Pay"
      },
      {
        $group: {
          _id: {
            serviceId: "$_id",
            payMonth: "$Pay.PayMonth"
          },
          sum: {
            $sum: "$Pay.PaySum"
          }
        }
      }
    ])
    

    Note that this will group pays from the same month (i.e. 12) from different years within the same group. If you want to differentiate them, you will have to add the year within _id of the group:

    _id: {
      serviceId: "$_id",
      payMonth: "$Pay.PayMonth",
      payYear: "$Pay.PayYear"
    }