Mongodb 聚合 -unwind 然后分组(查找唯一计数)
Mongodb Aggegrate -unwind and then group(Find unique count)
我有以这种格式存储的数据。我想在日期找到唯一的 msisdn。即,依靠日期
上的唯一 msisdn
{
"_id" : ObjectId("5e551b2e63a0f1fc55f026dd"),
"dateHour" : "2020-02-25 13",
"detail" : [
{
"campaignId" : "5e4a937b459418737cc1dfa5",
"timestamp" : "2020-02-25 13:03:626",
"msisdn" : "050920305373677038659253736080036024-1582133696781",
},
{
"campaignId" : "5e4a937b459418737cc1dfa5",
"timestamp" : "2020-02-2025 13:04:626",
"msisdn" : "050920305373677038659253736080036024-1582133696781",
},
{
"campaignId" : "5e4a937b459418737cc1dfa5",
"timestamp" : "2020-02-25 13:06:626",
"msisdn" : "050920305373677038659253-1582133696781",
}
]
}
您可以执行以下操作
[
{
$unwind: "$detail"
},
{
$addFields: {
"dHr": {
$substr: [
"$dateHour",
0,
10
]
}
}
},
{
$group: {
_id: "$dHr",
msisdn: {
$addToSet: "$detail.msisdn"
}
}
},
{
$project: {
_id: 0,
date: "$_id",
count: {
$size: "$msisdn"
}
}
}
]
我有以这种格式存储的数据。我想在日期找到唯一的 msisdn。即,依靠日期
上的唯一 msisdn{
"_id" : ObjectId("5e551b2e63a0f1fc55f026dd"),
"dateHour" : "2020-02-25 13",
"detail" : [
{
"campaignId" : "5e4a937b459418737cc1dfa5",
"timestamp" : "2020-02-25 13:03:626",
"msisdn" : "050920305373677038659253736080036024-1582133696781",
},
{
"campaignId" : "5e4a937b459418737cc1dfa5",
"timestamp" : "2020-02-2025 13:04:626",
"msisdn" : "050920305373677038659253736080036024-1582133696781",
},
{
"campaignId" : "5e4a937b459418737cc1dfa5",
"timestamp" : "2020-02-25 13:06:626",
"msisdn" : "050920305373677038659253-1582133696781",
}
]
}
您可以执行以下操作
[
{
$unwind: "$detail"
},
{
$addFields: {
"dHr": {
$substr: [
"$dateHour",
0,
10
]
}
}
},
{
$group: {
_id: "$dHr",
msisdn: {
$addToSet: "$detail.msisdn"
}
}
},
{
$project: {
_id: 0,
date: "$_id",
count: {
$size: "$msisdn"
}
}
}
]