本文介绍了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独特的聚合
发布评论