MongoDB独特的聚合

编程入门 行业动态 更新时间:2024-10-25 19:30:41
本文介绍了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独特的聚合

本文发布于:2023-11-22 09:43:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616935.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:独特   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!