Mongo DB - 群组状态并使用聚合获得总计数
我已经创建了一个收集帖子,并添加了如下所示的文档。Mongo DB - 群组状态并使用聚合获得总计数
[{ "title" : "MongoDB-Overview",
"status" : "created",
"postBy" : "sukesh"
}, {
"title" : "MongoDB-Collection",
"status" : "created",
"postBy" : "sukesh"
}, {
"title" : "MongoDB-Document",
"status" : "approved",
"postBy" : "sukesh"
}, {
"title" : "MongoDB-Database",
"status" : "approved_pending",
"postBy" : "ramesh"
}, {
"title" : "MongoDB-Query",
"status" : "deleted",
"postBy" : "suresh"
}]
我需要使用聚合函数,将计算,
1.总的职位分配给特定的人(这里只sukesh)和
2.总状态的次数,如果状态不那么分配给它会返回0.
像下面一样。
{ "postby": "sukesh"
"totalPost": 4,
"status": {
"created": 2
"approved": 1,
"approved_pending": 0,
"deleted": 1
}
}
请帮我解决问题。
回答:
我不认为这是可能正是你想要的,但你可以尝试,如果你可以使用这个:
db.collection.aggregate([ {
$group: {
_id: "$postBy",
count: { $sum: 1},
status: { $push: "$status"}
}
},
{ $unwind: "$status"},
{
$group: {
_id: { "postby": "$_id", status: "$status" },
scount: { $sum: 1},
count: {$first: "$count"}
}
},
{$group: {
_id: "$_id.postby",
total: {$first: "$count"},
status: {$push: { type: "$_id.status", count: "$scount" }},
}},
{
$project: {
_id: 0,
postby: "$_id",
totalPost: "$total",
status: 1
}
}
])
回答:
您可以使用下面聚集。
$group
按状态和postBy和每个postBy的计数状态然后$group
推动创建状态和计数阵列和总和所有状态计数以获得总数。
db.collection_name.aggregate([ {"$group":{
"_id":{"postBy":"$postBy","status":"$status"},
"count":{"$sum":1}
}},
{"$group":{
"_id":"$_id.postBy","totalPost":{"$sum":"$count"},
"status":{"$push":{"status":"$_id.status","count":"$count"}}
}}])
以上是 Mongo DB - 群组状态并使用聚合获得总计数 的全部内容, 来源链接: utcz.com/qa/266671.html