简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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