- MongoDB官方文档中文版
- MongoDB中文手册说明
- MongoDB简介
- 安装 MongoDB
- The mongo Shell
- MongoDB CRUD 操作
- 聚合
- 数据模型
- 事务
- 索引
-  安全   - 安全检查列表
- 启用访问控制
- 身份验证
- 基于角色的访问控制
- TLS / SSL(传输加密)
- 静态加密
- 客户端字段级加密
- 审计
- 网络和配置强化
- 实现字段级别修订
- 安全参考
- 附录
 
- 变更流
- 复制
- 分片   - 分片键
- 哈希分片
- 范围分片
- 区
- 管理分片区
- 按位置细分数据
- 用于更改SLA或SLO的分层硬件
- 按应用或客户细分数据
- 仅插入工作负载的分布式本地写入
- 管理分片区
- 使用块进行数据分区
- 在分片集群中拆分数据块
 
- 管理
-  存储   -  存储引擎   - 日志记录
- 管理日志记录   - GridFS
 
 
- FAQ:MongoDB 存储
 
-  存储引擎   
- 参考   - 运算符
- 查询与映射运算符
- 更新运算符
- 聚合管道阶段
-  聚合管道操作符   - $abs (aggregation)
- $acos (aggregation)
- $acosh (aggregation)
- $add (aggregation)
- $addToSet (aggregation)
- $allElementsTrue (aggregation)
- $and (aggregation)
- $anyElementTrue (aggregation)
- $arrayElemAt (aggregation)
- $arrayToObject (aggregation)
- $asin (aggregation)
- $asinh (aggregation)
- $atan (aggregation)
- $atan2 (aggregation)
- $atanh (aggregation)
- $avg (aggregation)
- $ceil (aggregation)
- $cmp (aggregation)
- $concat (aggregation)
- $concatArrays (aggregation)
- $cond (aggregation)
- $convert (aggregation)
- $cos (aggregation)
- $dateFromParts (aggregation)
- $dateToParts (aggregation)
- $dateFromString (aggregation)
- $literal (aggregation)
 
- 查询修饰符
- 数据库命令
- 聚合命令
- 地理空间命令
- 查询和写操作命令
- 查询计划缓存命令
- 认证命令
- 用户管理命令
- 角色管理命令
- 复制命令
- 分片命令
- 会话命令
- 管理命令
- 诊断命令
- 免费监控命令
- 系统事件审计命令
- mongo Shell 方法
-  集合方法   - db.collection.aggregate()
- db.collection.bulkWrite()
- db.collection.copyTo()
- db.collection.count()
- db.collection.countDocuments()
- db.collection.estimatedDocumentCount()
- db.collection.createIndex()
- db.collection.createIndexes()
- db.collection.dataSize()
- db.collection.deleteOne()
- db.collection.deleteMany()
- db.collection.distinct()
- db.collection.drop()
- db.collection.dropIndex()
- db.collection.dropIndexes()
- db.collection.ensureIndex()
- db.collection.explain()
- db.collection.find()
- db.collection.findAndModify()
- db.collection.findOne()
- db.collection.findOneAndDelete()
- db.collection.findOneAndReplace()
- db.collection.findOneAndUpdate()
- db.collection.getIndexes()
- db.collection.getShardDistribution()
- db.collection.getShardVersion()
- db.collection.insert()
- db.collection.insertOne()
- db.collection.insertMany()
- db.collection.isCapped()
- db.collection.latencyStats()
- db.collection.mapReduce()
- db.collection.reIndex()
- db.collection.remove()
- db.collection.renameCollection()
- db.collection.replaceOne()
- db.collection.save()
- db.collection.stats()
- db.collection.storageSize()
- db.collection.totalIndexSize()
- db.collection.totalSize()
- db.collection.update()
- db.collection.updateOne()
- db.collection.updateMany()
- db.collection.watch()
- db.collection.validate()
 
- 词汇表
- 默认的MongoDB端口
- 默认的MongoDB读/写关注
- 服务器会话
 
- MongoDB驱动
- FAQ
- 联系我们
- 更多资料   - [快学Mongo]
- [Mongo问题讨论区]
- [Mongo 驱动使用手册]
 
- 本书使用 GitBook 发布
使用 Zip Code 数据集进行聚合
使用 Zip Code 数据集进行聚合
在本页面
本文档中的示例使用zipcodes集合。该系列可在以下网址获得:media.mongodb.org/zips.json。使用mongoimport将此数据集加载到mongod实例中。
数据模型
zipcodes集合中的每个文档都具有以下形式:
{
  "_id": "10280",
  "city": "NEW YORK",
  "state": "NY",
  "pop": 5574,
  "loc": [
    -74.016323,
    40.710537
  ]
}
- _id字段将 zip code 保存为 string。
- city字段包含 city name。一个城市可以有多个与之关联的 zip code,因为城市的不同部分可以各自具有不同的 zip code。
- state字段包含两个字母 state 缩写。
- pop字段包含人口。
- loc字段将位置保存为纬度经度对。
aggregate()方法
以下所有示例都使用mongo shell 中的aggregate()帮助程序。
aggregate()方法使用聚合管道将文档处理为聚合结果。 聚合管道由多个阶段组成,每个阶段在文档沿着管道传递时都会对其进行处理。文档按顺序通过各个阶段。
mongo shell 中的aggregate()方法在聚合数据库命令提供了一个包装器。有关用于数据聚合操作的更惯用的界面,请参阅驱动的文档。
返回人口超过 1000 万的国家
以下聚合操作将返回总人口超过 1000 万的所有州:
db.zipcodes.aggregate( [
    { $group: { _id: “$state“, totalPop: { $sum: “$pop“ } } },
    { $match: { totalPop: { $gte: 10*1000*1000 } } }
] )
在此 example 中,聚合管道包含$group阶段,后跟$match阶段:
- 阶段按state字段对zipcode集合的文档进行分组,为每个 state 计算totalPop字段,并为每个唯一的 state 输出文档。
新的 per-state 文档有两个字段:_id字段和totalPop字段。 _id字段包含state的 value即: group by field。 totalPop字段是一个计算字段,包含每个 state 的总人口。要计算 value,$group使用$sum operator 为每个 state 添加填充字段(pop)。
在$group阶段之后,管道中的文档类似于以下内容:
{
    “_id“ : “AK“,
    “totalPop“ : 550043
}
此聚合操作的等效SQL是:
SELECT state, SUM(pop) AS totalPop
    FROM zipcodes
    GROUP BY state
    HAVING totalPop >= (10*1000*1000)
[success] 也可以看看
按 State 返回平均城市人口
以下聚合操作返回每个 state 中城市的平均人口数:
db.zipcodes.aggregate( [
    { $group: { _id: { state: “$state“, city: “$city“ }, pop: { $sum: “$pop“ } } },
    { $group: { _id: “$_id.state“, avgCityPop: { $avg: “$pop“ } } }
] )
在这个 example 中,聚合管道包含$group阶段,后跟另一个$group阶段:
在管道中的这个阶段之后,文档类似于以下内容:
{
    “_id“ : {
        “state“ : “CO“,
        “city“ : “EDGEWATER“
    },
    “pop“ : 13154
}
- 第二个$group阶段通过_id.state字段(i.e._id文档中的state字段)对管道中的文档进行分组,使用$avg表达式计算每个 state 的平均城市人口(avgCityPop),并为每个 state 输出一个文档。
此聚合操作产生的文档类似于以下内容:
{
    “_id“ : “MN“,
    “avgCityPop“ : 5335
}
[success] 也可以看看
按 State 返回最大和最小城市
以下聚合操作按每个 state 的填充返回最小和最大的城市:
db.zipcodes.aggregate( [
    { 
        $group:{
            _id: { state: “$state“, city: “$city“ },
            pop: { $sum: “$pop“ }
        }
    },
    { $sort: { pop: 1 } },
    { 
        $group:{
            _id : “$_id.state“,
            biggestCity:  { $last: “$_id.city“ },
            biggestPop:   { $last: “$pop“ },
            smallestCity: { $first: “$_id.city“ },
            smallestPop:  { $first: “$pop“ }
        }
    },
    // the following $project is optional, and
    // modifies the output format.
    { 
        $project:{ 
            _id: 0,
            state: “$_id“,
            biggestCity:  { name: “$biggestCity“,  pop: “$biggestPop“ },
            smallestCity: { name: “$smallestCity“, pop: “$smallestPop“ }
        }
    }
] )
在此 example 中,聚合管道包含$group阶段,$sort阶段,另一个$group阶段和$project阶段:
在管道的这个阶段,文档类似于以下内容:
{
    “_id“ : {
        “state“ : “CO“,
        “city“ : “EDGEWATER“
    },
    “pop“ : 13154
}
- $sort阶段通过 - popfield value 对管道中的文档进行排序,从最小到最大; 即:通过增加 order。此操作不会更改文档。
- 下一个$group阶段按 - _id.state字段(即:- _id文档中的- state字段)对 now-sorted 文档进行分组,并为每个 state 输出一个文档。
该阶段还为每个 state 计算以下四个字段。使用$last表达式,$group operator 创建biggestCity和biggestPop字段,用于存储人口和人口最多的城市。使用$first表达式,$group operator 创建smallestCity和smallestPop字段,用于存储人口和人口最少的城市。
在管道的这个阶段,文件类似于以下内容:
{
    “_id“ : “WA“,
    “biggestCity“ : “SEATTLE“,
    “biggestPop“ : 520096,
    “smallestCity“ : “BENGE“,
    “smallestPop“ : 2
}
- 最后的$project阶段将_id字段重命名为state,并将biggestCity,biggestPop,smallestCity和smallestPop移动到biggestCity和smallestCity嵌入文档中。
此聚合操作的输出文档类似于以下内容:
{
    “state“ : “RI“,
    “biggestCity“ : {
        “name“ : “CRANSTON“,
        “pop“ : 176404
    },
    “smallestCity“ : {
        “name“ : “CLAYVILLE“,
        “pop“ : 45
    }
}
| [1] | 一个城市可以有多个与之关联的 zip code,因为城市的不同部分可以各自具有不同的 zip code。 | 
译者:李冠飞
校对:李冠飞
Copyright © 上海锦木信息技术有限公司 all right reserved,由 MongoDB汉化小组 提供技术支持文件修订时间: 2020-10-11 20:53:05
 
                         
                                

