聚合在控制台而不是节点中工作?

Aggregation working in console but not node?

我对 node.js(Javascript 也是)完全陌生,所以匿名函数、回调之类的想法对我来说完全陌生,我还在摸索围绕这一切......所以说请对我放轻松! :)

我得到了以下查询,我可以在 mongo 控制台中毫无问题地使用它:

db.warmod_events.aggregate({ $match: {
    $and: [
        { "match.id": 1 },
        { "match.event.player.name": 'xxx' },
        { "match.event.event": 'round_stats' }
    ]
} },
{ $group: { _id : null, kills : { $sum: "$match.kills" } } });

通过阅读 mongo 节点驱动程序文档(似乎有点简短)这是我想出的,但由于某种原因它从来没有 returns 任何东西,查询结果是总是空的,我不确定为什么?

var getKills = function (db, callback) {
  var collection = db.collection('warmod_events');
  collection.aggregate(
      [
        {
          $match: {
            and: [
              {"match.matchId": 1},
              {"match.event.player.name": 'Jim'},
              {"match.event.event": 'round_stats'}
            ]
          }
        },
        {
          $group: {
            "_id": null, kills: {$sum: "$match.kills"}
          }
        }
      ], function (err, result) {
        console.dir(result);
        callback(result);
      });
};

集合中的文档示例:

{
    "match": {
        "event": {
            "timestamp": "2015-06-03 15:02:22",
            "event": "round_stats",
            "round": 1,
            "player": {
                "name": "Jim",
                "userId": 45,
                "uniqueId": "BOT",
                "team": 2
            },
            "shots": 0,
            "hits": 0,
            "kills": 0,
            "headshots": 0,
            "tks": 0,
            "damage": 0,
            "assists": 0,
            "assists_tk": 0,
            "deaths": 0,
            "head": 0,
            "chest": 0,
            "stomach": 0,
            "leftArm": 0,
            "rightArm": 0,
            "leftLeg": 0,
            "rightLeg": 0,
            "generic": 0
        },
        "matchId": 1
    }
}

你的 $match 中的 and 应该是 $and 而不是:

$match: {
    $and: [
        {"match.matchId": 1},
        {"match.event.player.name": 'Jim'},
        {"match.event.event": 'round_stats'}
    ]
}

但是,因为您所有的 $and 术语都使用唯一键,所以您实际上不需要使用 $and 并且可以将其简化为:

$match: {
    "match.matchId": 1,
    "match.event.player.name": 'Jim',
    "match.event.event": 'round_stats'
}