2017-12-27 1835 views
0

我已經創建了一個收集帖子,並添加了如下所示的文檔。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 
    }  
} 

請幫我解決問題。

回答

0

我不認爲這是可能正是你想要的,但你可以嘗試,如果你可以使用這個:

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 
    } 
} 
]) 
+0

感謝亞歷克斯撰寫完美的聚合功能,並作出如此快速的迴應,您讓我的一天。 –

+0

沒問題的隊友! –

0

您可以使用下面聚集。

$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"}} 
}}])