Mongodb使用 aggregation 处理数据的分组、聚合、统计。根据官网来说明 Aggregation Pipeline 的情况,和解决自己的工作问题。
官网地址:
https://docs.mongodb.com/manual/core/aggregation-pipeline/
1. 示例 mongo 数据
"_id" : ObjectId("5f0ff352c87ded750a7582e5"),
"mPlateNumber" : "B86A97",
"mobileCodeList" : [
{
"code" : "460010000000720",
},
{
"code" : "460010000000721",
},
{
"code" : "460010000000722",
}
]
}
/* 2 */
{
"_id" : ObjectId("5f0ff352c87ded750a7582e6"),
"mPlateNumber" : "B86A97",
"mobileCodeList" : [
{
"code" : "460010000000720",
}
]
}
/* 3 */
{
"_id" : ObjectId("5f0ff352c87ded750a7582e7"),
"mPlateNumber" : "A9H850",
"mobileCodeList" : [
{
"code" : "460010000000722",
}
]
}
2. 要求:筛选 mPlateNumber ,根据 mobileCodeList 中的 code分组,统计每组code 出现的次数,并降序排列
3. 语句实现
db.getCollection('car').aggregate([
{ $match: { mPlateNumber: "B86A97" } },
{ $unwind: "$mobileCodeList" },
{ $group: { _id: "$mobileCodeList.code", total: { $sum: 1 } } },
{ $sort: { total : -1}}
]);
4. 结果显示
/* 1 */
{
"_id" : [
"460010000000720"
],
"total" : 2.0
}
/* 2 */
{
"_id" : [
"460010000000721",
],
"total" : 1.0
}
/* 3 */
{
"_id" : [
"460010000000722"
],
"total" : 1.0
}
5. 分析
aggregate 从上到下依次执行,先使用 m a t c h 筛 选 出 符 合 条 件 的 数 据 , match 筛选出符合条件的数据, match筛选出符合条件的数据,unwind 把数组字段输出成单个文件,再使用 g r o u p 按 照 c o d e 分 组 , group按照 code 分组, group按照code分组,sum 统计每组的个数,最后 $sort 排序显示出来。在大数据量的操作中,最好是把一次过滤量大的条件放到前面,这样运算起来快。这里我们使用到了四个 Stage,比较常用的还有 $count, $project 等。
Aggregation 的功能强大,比 map reduce的效率更高,在使用的时候经常要翻看文档,查查 stage,以优雅的语句完成任务。