2014-01-24 254 views
0

我需要在mongo中的查詢幫助,我想獲取posts標籤,其中status: 'accepted後,將標籤分組並按事件排序。mongodb聚合,組和排序

db.collection('Posts').aggregate([{ 
     $project: { 
       tags: 1 
     } 
}, { 
     $unwind: "$tags" 
}, { 
     $group: { 
       _id: { 
         tag: "$tags" 
       }, 
       count: { 
         $sum: 1 
       } 
     } 
}], function (error, result) { 
     // do stuff 
}); 

這工作,但他們不通過count字段順序,我不知道如何選擇只有那些狀態accepted職位。有任何想法嗎?

回答

0

爲了按狀態過濾帖子,您可以使用$match運算符。按數量排序,您應該使用$sort運營商。

更新查詢的版本應該是這樣的:

db.collection('Posts').aggregate([ 
{$match : {status : "accepted"}}, 
{$project: {tags: 1}}, 
{$unwind: "$tags"}, 
{$group: {_id: {tag: "$tags"},count: {$sum: 1}}}, 
{$sort : {count : 1}}], 
function (error, result) { 
     // do stuff 
});