Mongodb根据状态汇总博客文章

时间:2015-07-27 09:16:40

标签: mongodb mongoose aggregation-framework

我有一个名为“博客”的集合,我希望根据3个状态计算每个用户博客,例如:已发布,待定和已批准。结果看起来应该是


    [{
     "_id" : ObjectId('dshe1hhdsa12dashe21dqs'),
     "blogId" : 'dhsad78sa6dsa66ds6ds6ds8ds',
     "published" : 10,
     "approved" : 15,
     "pending" : 5
    },
    {
     "_id" : ObjectId('dshe1hhdsa12dashe21dqs'),
     "blogId" : 'dhsad78sa6dsa66ds6ds6ds8ds',
     "published" : 10,
     "approved" : 15,
     "pending" : 5
    }]

我想为此使用db.collection.aggregate()。

编辑:我试过这个


    db.blog.aggregate([ 
    { $match: { status: { $in : ['Published', 'Approved', 'Pending']}}},
    { $project : { _id: 1, blogId: 1, status: 1} }]).pretty();

1 个答案:

答案 0 :(得分:1)

好的,我得到了解决方案,我们走了。


    var query = [
      { 
        $match: 
          { 
            status: { $in : ['Published', 'Approved', 'Pending']}
          }
      },
      {
        $group: {
          _id: { 
            blogId:"$blogId"
          }, 
          published: {
            $sum:{
              $cond:[
                {$eq:["$status","Published"]}, 
                1, 
                0
              ]
            }
          }, 
          approved: {
            $sum: { 
              $cond:[
                {$eq:["$status","Approved"]}, 
                1, 
                0
              ]
            }
          },
          pending: {
            $sum: { 
              $cond:[
                {$eq:["$status","Pending"]}, 
                1, 
                0
              ]
            }
          }  
        } 
      },
      {
        $project: {
         _id: 0, 
         blogId: "$_id.blogId", 
         published: "$published", 
         approved: "$approved",
         pending: "$pending"
        }
      }
    ];

    db.blog.aggregate(query);