PHP MongoDB聚合:只有当值大于0时,如何$ sum?

时间:2016-06-15 09:59:58

标签: php mongodb aggregation-framework

我正在使用PHP访问我记录了游戏玩家的MongoDB集合:

{username: "John", stats: {games_played: 79, boosters_used: 1, crystals: 5}},
{username: "Bill", stats: {games_played: 0, boosters_used: 0, crystals: 20}},
{username: "Jane", stats: {games_played: 154, boosters_used: 14, crystals: 37}},
{username: "Sarah", stats: {games_played: 22, boosters_used: 0, crystals: 0}},
{username: "Thomas", stats: {games_played: 0, boosters_used: 0, crystals: 20}},

在我的PHP脚本中,我这样做是为了获得总和和平均值:

$filter = [
    ['$group' => [
        'Players count' => ['$sum' => 1],
        'avgGamesPlayed' => [
            '$avg' => '$stats.games_played'
        ],
        'TotalGamesPlayed' => [
            '$sum' => '$stats.games_played'
        ],
    ]],
    ['$sort' => [get('sort', 'count') => (int) get('sort_order', -1)]],
];

$options = [];

$m->aggregate($filter, $options);

如果我回复结果,我将获得:

Players count = 5;
avgGamesPlayed = 51;
TotalGamesPlayed = 255;

我想要的是获得 stats.games_played大于0 $ sum 。在这种特殊情况下结果为3。

我知道如果我使用查找'$ gt'=>,则可以执行此操作0 但我真的需要坚持使用聚合。我想做这样的事情:

'Players count' => ['$sum' => ['$gt' => 0]],

但它不起作用,我已经在这里呆了几个星期了,我读了文档,但我不熟悉MongoDB,这就是为什么我要求你的知识。

如果你对这个问题有了答案,我会非常感激,谢谢。

1 个答案:

答案 0 :(得分:2)

这是 $cond 运算符非常适合的地方。您可以将其用作 $sum 运算符文档中的表达式,该表达式将评估逻辑,并在var array 3=[{name: 'client', default: false}] 字段求值为0时返回0,否则返回0(即> 0)。

遵循这种方法将产生欲望的结果:

$stats.games_played