mongodb - MongoDB:使用 id=null 分组
问题描述
我有一个此类文档的集合:
enter code here
{ "_id": "10280",
"city": "NEW YORK",
"state": "NY",
"pop": 5574,
"loc": [
-74.016323,
40.710537 ]
}
我必须进行这个 mongoDB 查询:
返回邮政编码数量最多的城市
我的解决方案基于此: 1. 为每个城市汇总邮政编码(按城市分组。记住邮政编码是 _id) 2. 按 null 分组以生成 $max (使用一个文档) 3. 项目城市和邮政编码具有最大数量的城市的代码。
这是我的查询:
db.zipcodes.aggregate([
{"$group": {_id:"$city", numberZipCodes: {$sum:1}}},
{"$group": {_id: null, maxNumber: {$max: "$numberZipCodes"}}},
{"$project":{ "city": "$_id.city", "maxNumber":1, "_id":0, "city":1}}])
但显然我没有 _id.city 值。我怎样才能记住它??
解决方案
db.zipcodes.aggregate([{
$group: {
_id: "$city",
totalZipCodes: {
$sum: 1
}
}
}, {
$sort: {
totalZipCodes: -1
}
},
{
$limit: 1
}
])
上述聚合管道有 2 个阶段:
- 按城市分组总邮政编码
- 使用邮政编码的数量从阶段到排序所有记录,返回具有最大邮政编码的城市
推荐阅读
- php - Google 照片 api 的身份验证范围错误
- python - 使用 OpenPyXL 复制工作表不会保留数据验证
- ios - Firebase 通知限制 iOS
- azure - 在 Azure 资源管理器 (ARM) 中从 KV 安装多个版本的证书
- powershell - Chef infra config 的 Powershell 问题:动态值
- python - 使用 Tkinter (Python) 在 Canvas 上绘制、调整大小和移动三角形
- node.js - 节点和 elasticSearch 客户端 - 客户端注意到服务器不是 Elasticsearch 支持的发行版
- excel - 如何取消“Application.OnTime Now + TimeValue”
- html - 在 angular10 中允许使用 latin1 字符作为输入
- haskell - 如果 a 有 Monoid,是否可以为 Identity a 编写 Alternative 实例?