我正在使用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,这就是为什么我要求你的知识。
如果你对这个问题有了答案,我会非常感激,谢谢。