MongoDB独特的聚合 [英] MongoDB distinct aggregation
本文介绍了MongoDB独特的聚合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在研究一个查询,以查找每个州的邮政编码最多的城市:
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.
这是因为我的ID中有州吗?我可以做类似distinct("_id.state
的事情吗?
Is this because I have state in the id? Can I do something like distinct("_id.state
?
推荐答案
不同的聚合框架不可互操作.
Distinct and the aggregation framework are not inter-operable.
相反,您只想要:
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'}}}
]);
这篇关于MongoDB独特的聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文