计算 mongodb 中字段的非重复计数
Calculate distinct count on fields in mongodb
我有以下合集:
[{
"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 计数?
你需要做的是在小组赛阶段使用$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
}
}
])
我有以下合集:
[{
"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 计数?
你需要做的是在小组赛阶段使用$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
}
}
])