https://blog.csdn.net/hwhaocool/article/details/81741919
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" : "AAA"
},
"count" : 2.0
}
虽然数据是对的,但是结果有两条数据,不符合我们的标题,
我们希望的是,在一条数据里输出两个值,类似于
{
"count" : 2.0,
"AAACount": 2.0,
"BBBCount": 1.0
}
3.3 此时,就是合并数据的操作了
但是,我搜了好久的资料,不知道怎么合并,放弃之
同事提醒了我,用project试试
3.4 增加字段
代码:
db.test_yellow.aggregate([
{
$match : {
"agentId" : "123",
"userId" : "yellow"
}
},
{
$project: {
_id: 1,
"targetType": 1,
"agentId": 1,
"userId": 1,
AType: {
$cond: {
if: {$eq: ["AAA", "$targetType"]},
then: 1,
else: 0
}
},
BType: {
$cond: {
if: {$eq: ["BBB", "$targetType"]},
then: 1,
else: 0
}
}
}
}
])
结果如下:
可以看到根据不同的类型,新增了字段,并且把自己设置数字1
方便后面统计
3.5 group 统计
代码:
db.test_yellow.aggregate([
{
$match : {
"agentId" : "123",
"userId" : "yellow"
}
},
{
$project: {
_id: 1,
"targetType": 1,
"agentId": 1,
"userId": 1,
AType: {
$cond: {
if: {$eq: ["AAA", "$targetType"]},
then: 1,
else: 0
}
},
BType: {
$cond: {
if: {$eq: ["BBB", "$targetType"]},
then: 1,
else: 0
}
}
}
},
{
$group: {
_id: {
"targetType": "$targetType"
},
totalCount: {$sum: 1},
ACount: {$sum: "$AType"},
BCount: {$sum: "$BType"}
}
}
])
输出如下:
4. 最后
综上所述,可以写出最终的代码:
db.test_yellow.aggregate([
{
$project: {
_id: 1,
"targetType": 1,
"agentId": 1,
"userId": 1,
AType: {
$cond: {
if: {$eq: ["AAA", "$targetType"]},
then: 1,
else: 0
}
},
BType: {
$cond: {
if: {$eq: ["BBB", "$targetType"]},
then: 1,
else: 0
}
}
}
},
{
$group: {
_id: {
"agentId": "$agentId",
"userId": "$userId"
},
agentId: {$first: "$agentId"},
userId: {$first: "$userId"},
totalCount: {$sum: 1},
ACount: {$sum: "$AType"},
BCount: {$sum: "$BType"}
}
}
])
输出
可以看到输出结果是符合预期的