MongoDB 不同聚合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16368638/
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 13:12:16  来源:igfitidea点击:

MongoDB distinct aggregation

mongodbdistinct

提问by Lemonio

I'm working on a query to find cities with most zips for each state:

我正在查询以查找每个州的邮编最多的城市:

db.zips.distinct("state", db.zips.aggregate([ {$group:{_id:{state:"$state", city:"$city"},numberOfzipcodes:{$sum:1}}}, {$sort:{numberOfzipcodes:-1}}]))

The aggregate part of the query seems to work fine, but when I add the distinct I get an empty result.

查询的聚合部分似乎工作正常,但是当我添加 distinct 时,我得到一个空结果。

Is this because I have state in the id? Can I do something like distinct("_id.state?

这是因为我在 id 中有状态吗?我可以做类似的事情distinct("_id.state吗?

回答by dam1

You can use $addToSetwith the aggregation framework to count distinct objects.

您可以将$addToSet与聚合框架一起使用来计算不同的对象。

For example:

例如:

db.collectionName.aggregate([{
    $group: {_id: null, uniqueValues: {$addToSet: "$fieldName"}}
}])

回答by Sammaye

Distinct and the aggregation framework are not inter-operable.

Distinct 和聚合框架不可互操作。

Instead you just want:

相反,您只想要:

db.zips.aggregate([ 
    {$group:{_id:{city:'$city', state:'$state'}, numberOfzipcodes:{$sum:1}}}, 
    {$sort:{numberOfzipcodes:-1}},
    {$group:{_id:'$_id.state', city:{$first:'$_id.city'}, 
              numberOfzipcode:{$first:'$numberOfzipcodes'}}}
]);

回答by Surendranath Reddy K

SQL Query: (group by & count of distinct)

SQL 查询:(分组依据和不同计数)

select city,count(distinct(emailId)) from TransactionDetails group by city;

Equivalent mongo query would look like this:

等效的 mongo 查询如下所示:

db.TransactionDetails.aggregate([ 
{$group:{_id:{"CITY" : "$cityName"},uniqueCount: {$addToSet: "$emailId"}}},
{$project:{"CITY":1,uniqueCustomerCount:{$size:"$uniqueCount"}} } 
]);

回答by Jeroen

You can call $setUnionon a single array, which also filters dupes:

您可以调用$setUnion单个数组,该数组还可以过滤重复项:

{ $project: {Package: 1, deps: {'$setUnion': '$deps.Package'}}}