Alon Alon - 1 month ago 14
Javascript Question

MongoDB aggregation always returns 0 values

The following query:

[{
$match: {
$and: [
{campaignID: "12345"},
{date: "2016-10-18"},
{hour: {$gte: 0}},
{hour: {$lte: 3}}
]
}
}
}]


returns the following (correct) data:

[{"_id":"580638b1e4b01c1a027e82c1","campaignID":"12345","date":"2016-10-18",
"hour":0,"foo":10,"bar":10},
{"_id":"580638cbe4b01c1a027e82c2","campaignID":"12345","date":"2016-10-18",
"hour":1,"foo":11,"bar":11},
{"_id":"580638e5e4b01c1a027e82c3","campaignID":"12345","date":"2016-10-18",
"hour":2,"foo":12,"bar":12},
{"_id":"580638efe4b01c1a027e82c4","campaignID":"12345","date":"2016-10-18",
"hour":3,"foo":13,"bar":13}]


But the following query:

[
{
$match: {
$and: [
{campaignID: "12345"},
{date: "2016-10-18"},
{hour: {$gte: 0}},
{hour: {$lte: 3}}
]
}
},
{
$group: {
_id: campaignID,
foo:{$sum: "foo"},
bar:{$sum: "bar"}
}
}
]


returns the following (wrong) data:

[{"_id":"sA48VsoQyuuEDVI5lr4loL31mqoCRT","foo":0,"bar":0}]


Both 'foo' and 'bar' are supposed to be 46 (10+11+12+13)

What am I doing wrong?

Answer

You should use $ with the field name to refer its value.

$group: {
    _id: "$campaignID",
    foo:{$sum: "$foo"},
    bar:{$sum: "$bar"}
}
Comments