0

我正在使用 Mongo Aggregate 对项目进行平均和总和

pipeline = [
    {$match: {///conditions here}},
    {$group: {_id: 'type', 'total': {'$sum':'$duration'}, 'avg': {'$sum':'$duration'}}},
  ]

聚合函数有效,但是对于 $sum 和 $avg 结果,有时我会得到负值。问题是数据库中的 $duration 是大整数。

我应该如何使它在这些大值上起作用?

4

1 回答 1

0

您可以通过将 NumberLong 值强制转换为浮点数来执行此操作,然后再尝试通过向它们添加浮点 0 来对它们求和,$project如下所示:

pipeline = [
    {$match: {///conditions here}},
    {$project: {type: 1, duration: {$add: ['$duration', 0.0]}}},
    {$group: {_id: 'type', 'total': {'$sum':'$duration'}, 'avg': {'$sum':'$duration'}}},
]
于 2013-07-29T00:25:09.550 回答