以下查询:
[{
$match: {
$and: [
{campaignID: "12345"},
{date: "2016-10-18"},
{hour: {$gte: 0}},
{hour: {$lte: 3}}
]
}
}
}]
返回以下(正确)数据:
[{"_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}]
但是以下查询:
[
{
$match: {
$and: [
{campaignID: "12345"},
{date: "2016-10-18"},
{hour: {$gte: 0}},
{hour: {$lte: 3}}
]
}
},
{
$group: {
_id: campaignID,
foo:{$sum: "foo"},
bar:{$sum: "bar"}
}
}
]
返回以下(错误)数据:
[{"_id":"sA48VsoQyuuEDVI5lr4loL31mqoCRT","foo":0,"bar":0}]
两个' foo'和' bar'应该是46(10 + 11 + 12 + 13)
我做错了什么?
答案 0 :(得分:3)
您应该使用带字段名称的$来引用其值。
$group: {
_id: "$campaignID",
foo:{$sum: "$foo"},
bar:{$sum: "$bar"}
}