Meteor响应式聚合

5

我希望为Transactions集合创建Meteor响应式聚合。

Transactions具有日期,因此我想按月份聚合数据。

代码如下:

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" });

});

当我执行此操作时,会提示错误:

错误:Meteor目前不支持除ObjectID以外的其他对象作为id

谢谢!


你尝试过简单地使用 _id: { $month: "$date" } 吗? - MasterAM
1个回答

2

您的$group子句是:

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

这会导致每个文档都有一个综合的_id{_id: {month: <someMonth>}, ...},其中每个_id都是一个对象,而不是ObjectID
在您的情况下,只需要{_id: <someMonth>, ...}即可。
可以通过以下方式进行分组来实现此目标:
'$group' : {
  '_id' : { $month: "$date" },
  ...
}

顺便提一下,如果你需要将 _id 作为字符串(我认为你确实需要这样做),你可以使用 $substr 进行转换:
'$group' : {
  _id: {$substr: [{$month: '$date'}, 0, 2]},
  ...
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接