在MongoDB GROUP BY中做一个HAVING的正确方法是什么? [英] What is the correct way to do a HAVING in a MongoDB GROUP BY?

查看:125
本文介绍了在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的所有字段,如下所示:



<对于(我在res中){if(res [i] .count> 1)printjson(res [i])}; pre>

除了在客户端使用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 to Mongo Aggregation conversion chart 值得加书签。


For what would be this query in SQL (to find duplicates):

SELECT userId, name FROM col GROUP BY userId, name HAVING COUNT(*)>1

I performed this simple query in MongoDB:

res = db.col.group({key:{userId:true,name:true}, 
                     reduce: function(obj,prev) {prev.count++;}, 
                     initial: {count:0}})

I've added a simple Javascript loop to go over the result set, and performed a filter to find all the fields with a count > 1 there, like so:

for (i in res) {if (res[i].count>1) printjson(res[i])};

Is there a better way to do this other than using javascript code in the client? If this is the best/simplest way, say that it is, and this question will help someone :)

解决方案

New answer using Mongo aggregation framework

After this question was asked and answered, 10gen released Mongodb version 2.2 with an aggregation framework. The new best way to do this query is:

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 has a handy SQL to Mongo Aggregation conversion chart worth bookmarking.

这篇关于在MongoDB GROUP BY中做一个HAVING的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆