Database

[{"_id":"1","storeCode":"111","kpiType":"trafficIn","trafficIn":{countValue:1}},{"_id":"2","storeCode":"111","kpiType":"trafficOut","trafficOut":{countValue:1}},{"_id":"3","storeCode":"222","kpiType":"trafficIn","trafficIn":{countValue:6}},{"_id":"4","storeCode":"222","kpiType":"trafficOut","trafficOut":{countValue:2}},{"_id":"5","storeCode":"333","kpiType":"trafficIn","trafficIn":{countValue:3}},{"_id":"6","storeCode":"333","kpiType":"trafficOut","trafficOut":{countValue:4}},{"_id":"7","storeCode":"111","kpiType":"trafficIn","trafficIn":{countValue:2}},{"_id":"8","storeCode":"222","kpiType":"trafficOut","trafficOut":{countValue:2}}]

Query

db.collection.aggregate([{$match:{$expr:{$in:[{"storeCode":"$storeCode","kpiType":"$kpiType"},[{"storeCode":"111","kpiType":"trafficIn"},{"storeCode":"222","kpiType":"trafficOut"}]]}}},{$group:{_id:{"storeCode":"$storeCode","kpiType":"$kpiType"},sum:{$sum:{$cond:[{$eq:["$kpiType","trafficIn"]},"$trafficIn.countValue","$trafficOut.countValue"]}}}}])

Result