我创建了一个集合帖子,并添加了如下所示的文档。
[{
"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"
}]我需要使用聚合函数来计算,
{
"postby": "sukesh"
"totalPost": 4,
"status": {
"created": 2
"approved": 1,
"approved_pending": 0,
"deleted": 1
}
}请帮我找到解决办法。
发布于 2017-12-27 18:36:50
我不认为这完全是你想要的,但你可以尝试一下,如果你能用这个:
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
}
}
])https://stackoverflow.com/questions/47996384
复制相似问题