我有一个名为ActivityCollection的集合。有很多领域 在它,但我想只有两个字段命名为Acitivity和 所有活动的标签。我也想计算总数 每个活动和标签的计数。为了更清楚 理解见下面的图片
答案 0 :(得分:0)
假设您的ActivityCollection中有以下数据模型:
{
"_id" : ObjectId("5a0c4894e465dc895af90d2c"),
"activity" : "Phone Call",
"tag" : "Addiction"
}
{
"_id" : ObjectId("5a0c48a2e465dc895af90d2d"),
"activity" : "Phone Call",
"tag" : "Family Issue"
}
{
"_id" : ObjectId("5a0c48aee465dc895af90d2e"),
"activity" : "Email",
"tag" : "Family Issue"
}
{
"_id" : ObjectId("5a0c48b9e465dc895af90d2f"),
"activity" : "Email",
"tag" : "Depression"
}
以下聚合作业将返回信息中心所需的数据:
根据活动计算:
db.ActivityCollection.aggregate([{$group:{_id:"$activity", count:{$sum:1}}}])
基于标记的计数:
db.ActivityCollection.aggregate([{$group:{_id:"$tag", count:{$sum:1}}}])
以下结果分别为:
基于活动:
{ "_id" : "Email", "count" : 2 }
{ "_id" : "Phone Call", "count" : 2 }
基于标签:
{ "_id" : "Depression", "count" : 1 }
{ "_id" : "Family Issue", "count" : 2 }
{ "_id" : "Addiction", "count" : 1 }