首页 > 解决方案 > 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 值。我怎样才能记住它??

标签: mongodbnosql

解决方案


    db.zipcodes.aggregate([{
            $group: {
                _id: "$city",
                totalZipCodes: {
                    $sum: 1
                }
            }
        }, {
            $sort: {
                totalZipCodes: -1
            }
        },
        {
            $limit: 1
        }
    ])

上述聚合管道有 2 个阶段:

  1. 按城市分组总邮政编码
  2. 使用邮政编码的数量从阶段到排序所有记录,返回具有最大邮政编码的城市

推荐阅读