在MongoDB GROUP BY中进行HAVING的正确方法是什么?

对于SQL中的这个查询(查找重复项):
SELECT userId, name FROM col GROUP BY userId, name HAVING COUNT(*)>1
我在MongoDB中执行了这个简单的查询:
res = db.col.group({key:{userId:true,name:true}, 
                     reduce: function(obj,prev) {prev.count++;}, 
                     initial: {count:0}})
我添加了一个简单的Javascript循环来遍历结果集,并执行了一个过滤器来查找count> 1的所有字段,如下所示:
for (i in res) {if (res[i].count>1) printjson(res[i])};
除了在客户端使用javascript代码之外,还有更好的方法吗? 如果这是最好/最简单的方式,说它是,这个问题将有助于某人:)     
已邀请:
使用Mongo聚合框架的新答案 在提出并回答了这个问题之后,10gen发布了带有聚合框架的Mongodb 2.2版本。执行此查询的新方法是:
db.col.aggregate( [
   { $group: { _id: { userId: "$userId", name: "$name" },
               count: { $sum: 1 } } },
   { $match: { count: { $gt: 1 } } },
   { $project: { _id: 0, 
                 userId: "$_id.userId", 
                 name: "$_id.name", 
                 count: 1}}
] )
10gen有一个方便的SQL到Mongo聚合转换图表值得书签。     

要回复问题请先登录注册