PHP MongoDB aggregation : how to $sum only when value is greater than 0?
<p>I am using PHP to access a MongoDB collection in which I have recorded players of a game :</p>

<pre><code>{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}},
</code></pre>

<p>In my PHP script I am doing this to get sums and averages :</p>

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

$options = [];

$m-&gt;aggregate($filter, $options);
</code></pre>

<p>If I echo the result I'll obtain :</p>

<pre><code>Players count = 5;
avgGamesPlayed = 51;
TotalGamesPlayed = 255;
</code></pre>

<p>What I would like to do is to get the <strong>$sum</strong> of players where  <strong>stats.games_played is greater than 0</strong>. In this particular case <strong>the result would be 3.</strong></p>

<p>I know that there is a possibility to do this if I use <strong>find</strong> and <strong>'$gt' => 0</strong> but I really need to stick with aggregate. Si I am trying to do something like this :</p>

<pre><code>'Players count' =&gt; ['$sum' =&gt; ['$gt' =&gt; 0]],
</code></pre>

<p>But it doesn't work and I'm stuck here for weeks now, I read the doc but I'm not that familiar with MongoDB, that's why I'm calling for your knowledges.</p>

<p>If you have the answer to this question I'd appreciate it a lot, thank you.</p>