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

我对node.js(也是Javascript)完全陌生,所以匿名函数,callback函数和类似的想法对我来说是一个完全陌生的东西,而且我还在为这个包裹着…所以请说容易在我身上! 🙂

我有以下查询我可以在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 } } 

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