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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5550253/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 12:02:44  来源:igfitidea点击:

What is the correct way to do a HAVING in a MongoDB GROUP BY?

group-bymongodbhavinghaving-clause

提问by shlomoid

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

对于 SQL 中的此查询是什么(查找重复项):

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

I performed this simple query in MongoDB:

我在 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:

我添加了一个简单的 Javascript 循环来遍历结果集,并执行一个过滤器来查找所有计数 > 1 的字段,如下所示:

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 :)

除了在客户端使用 javascript 代码之外,有没有更好的方法来做到这一点?如果这是最好/最简单的方法,请说是,这个问题会对某人有所帮助:)

回答by Old Pro

New answer using Mongo aggregation framework

使用 Mongo 聚合框架的新答案

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:

在这个问题被提出和回答之后,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 has a handy SQL to Mongo Aggregation conversion chartworth bookmarking.

10gen 有一个方便的SQL 到 Mongo 聚合转换图表,值得收藏。