mongo aggregate group, group使用

 1 var rs = db.fs.files.aggregate([
 2     {$group: {_id: '$metadata.cas', count: {$sum: 1}}},
 3     {$match: {count: {$gt: 1}}}
 4 ])
 5 
 6 //print(rs);
 7 for(var i in rs.result){
 8     var count = rs.result[i].count;
 9     var id = rs.result[i]._id;
10     
11     for(var j = 0; j < count - 1; j ++){
12         db.fs.files.remove({'metadata.cas': id}, true);
13     }
14 }
 1 db.runCommand({group: {
 2     ns: 'fs.files',
 3     key: {},
 4     initial: {'result': {}},
 5     $reduce: function(doc, out){
 6         if(doc.metadata.cas in out.result){
 7             out.result[doc.metadata.cas] ++;
 8     }else{
 9             out.result[doc.metadata.cas] = 1;
10     }
11     },
12     finalize: function(out){
13         for(key in out.result){
14             if(out.result[key] <= 1){
15         delete out.result[key];
16             }
17     }
18     }
19 }})

 

posted @ 2016-08-08 14:47  下一个雨季~  阅读(316)  评论(0编辑  收藏  举报