anditpainsme
anditpainsme

Reputation: 649

Aggregation working in console but not node?

I am totally new to node.js (and Javascript too), so the idea of anonymous functions, callbacks and the likes is a totally foreign to me and I'm still wrapping my head around it all... so that said please go easy on me! :)

I've got the following query I'm able to use in the mongo console without any issues:

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" } } });

From reading the mongo node driver documentation (which seems to be a little brief) this is what I came up with, but for some reason it never returns anything, the query result is always empty and I'm not sure why?

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

An example of a document in the collection:

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

Upvotes: 2

Views: 143

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

The and in your $match should be $and instead:

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

However, because all your $and terms use unique keys, you don't actually need to use $and and can simplify this to:

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

Upvotes: 1

Related Questions