1. 数据如下:
数据1:
2. 想要输出同一个 agentId 下面,每个userId,type是AAA的次数和BBB的次数
一上来可能有点复杂,我们一步一步慢慢来,先简化一下,好整理思路
3. 输出agentId是123,userId是yellow,type是AAA的次数和BBB的次数
3.1 先过滤一下
3.2 再分组
在SQL里面,语法是select count(a) from xx group by a
我们在MongoDB里写一下类似的
代码:
db.test_yellow.aggregate([
{
$match : {
"agentId" : "123",
"userId" : "yellow"
}
},
{
$group: {
_id: {
"targetType": "$targetType"
},
count: {
$sum:1}
}
}
])
输出为
{
"_id" : {
"targetType" : "BBB"
},
"count" : 1.0
}
{
"_id" : {
"targetType