我有以下收藏:
[{
"id": 1,
"activity_type": "view",
"user_id": 1
},
{
"id": 2,
"activity_type": "save",
"user_id": 1
},
{
"id": 3,
"activity_type": "save",
"user_id": 1
},
{
"id": 4,
"activity_type": "save",
"user_id": 2
}]
我需要得到這樣的結果:
[{
"activity_type": "view",
"count": 1,
"user_count": 1
},{
"activity_type": "save",
"count": 3,
"user_count": 2
}]
到目前為止,我達到了這一點:
db.getCollection('activities').aggregate([
{
$group:{_id:"$activity_type", count: {$sum: 1}}
},
{
$project:
{
_id: 0,
activity_type: "$_id",
count: 1
}
}
])
它給了我:
[{
"activity_type": "view",
"count": 1
},
{
"activity_type": "save",
"count": 3
}]
如何添加不同的 user_id 計數?
uj5u.com熱心網友回復:
您需要做的是$addToSet在小組階段使用來收集唯一 ID,然后在$project階段您可以使用$size來顯示正確的用戶數。
db.collection.aggregate([
{
$group: {
_id: "$activity_type",
count: {
$sum: 1
},
user_ids: {
"$addToSet": "$user_id"
}
}
},
{
$project: {
_id: 0,
activity_type: "$_id",
user_count: {
$size: "$user_ids"
},
count: 1
}
}
])
蒙戈游樂場
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/462457.html
