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

时间:2015-06-13 03:54:55

标签: javascript node.js mongodb aggregation-framework

我对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节点驱动程序文档(这似乎有点简短)这是我想出来的,但由于某种原因它永远不会返回任何东西,查询结果总是空的,我不知道为什么?

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
    }
}

1 个答案:

答案 0 :(得分:1)

and中的$match应改为$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'
}