Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor ReactiveAggregate

Tags:

mongodb

meteor

I want to create meteor reactive aggregation for Transactions collection.

The transactions has date, so i want to aggregate data by month.

The code is:

ReactiveAggregate(this, Transactions, [
    {
      $match: {
        'date': {
          $gte: new Date(startDate),
          $lt: new Date(endDate)
        }
      }
    },
    {
      '$group' :
      {
        '_id' : { month: { $month: "$date" }},
        'totalProfit': { $sum: "$totalProfit"},
        'totalSales': { $sum: "$totalSales" },
        'totalExpenses': { $sum: "$totalExpenses" },
        count: { $sum: 1 }
      }
    },
    {
      '$project':{
        date: '$date',
        totalProfit: '$totalProfit',
        totalSales: '$totalSales',
        totalExpenses: '$totalExpenses',
      }
    }
  ], { clientCollection: "report3MonthsTransactions" });

});

When i do this, it will prompt error:

Error: Meteor does not currently support objects other than ObjectID as ids

Thanks!

like image 951
Ramzan Rozali Avatar asked Oct 30 '22 04:10

Ramzan Rozali


1 Answers

Your $group clause is:

'$group' : {
  '_id' : { month: { $month: "$date" }},
  ...
}

which results in each document having a composite _id: {_id: {month: <someMonth>}, ...}, where each _id is an object that is indeed not an ObjectID.

In your case, having {_id: <someMonth>, ...} would suffice.

This can be achieved by grouping it as follows:

'$group' : {
  '_id' : { $month: "$date" },
  ...
}

By the way, if you need to have the _id as a string (and I think you do), you can use $substr to convert it:

'$group' : {
  _id: {$substr: [{$month: '$date'}, 0, 2]},
  ...
}
like image 195
MasterAM Avatar answered Nov 15 '22 10:11

MasterAM