简体   繁体   English

MongoDB聚合始终返回0值

[英]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) 'foo'和'bar'都应该是46(10 + 11 + 12 + 13)

What am I doing wrong? 我究竟做错了什么?

You should use $ with the field name to refer its value. 您应该在字段名称中使用$来引用其值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM