mongo-aggregate-nested-array 文档中嵌入了数组,此时就是要聚合这个嵌入的array。
- MongoDB 3.6
数据样本
{
"_id" : ObjectId("5aa63f7034cdbd6928f831ff"),
"domain" : "metacafe.com",
"cdn" : "LLNW",
"geo_bytes" : [
{
"bytes" : 223,
"geo" : "马耳他"
},
{
"bytes" : 446,
"geo" : "加拿大"
},
{
"bytes" : 892,
"geo" : "菲律宾"
},
{
"bytes" : 223,
"geo" : "西班牙"
}
],
"time" : 1520697600
}
geo_bytes
就是个嵌入的数组,geo
代表地区,bytes
代表流量,time
是时间戳,需求类似:计算一周之内流量的国家分布? ,查询描述就是 根据 geo 字段对 bytes 字段求和。
查询写法
db.getCollection('daily_coll').aggregate(
{"$match": {
"time": {"$gte": 1520697600, "$lt": 1520697601},
}},
{"$unwind": "$geo_bytes"},
{"$group": {
"_id": {
"geo": "$geo_bytes.geo"
},
"bytes": {"$sum": "$geo_bytes.bytes"}
}},
{"$project":{
"_id": 0,
"geo": "$_id.geo",
"bytes": "$bytes"
}},
{"$sort": {"bytes": -1}}
)
关键在于 $unwind
这个方法,文档地址 ,它的作用就是把 嵌入的array,提到当前的文档,把嵌入变成了扁平的结构。
上面的样本数据, 经过如下查询
db.getCollection('daily_coll').aggregate(
{"$match": {
"time": {"$gte": 1520697600, "$lt": 1520697601},
}},
{"$unwind": "$geo_bytes"}
)
结果这个数据会被拆分成4条
{
"_id" : ObjectId("5aa63f7034cdbd6928f831ff"),
"domain" : "metacafe.com",
"cdn" : "LLNW",
"geo_bytes" : {
"bytes" : 223,
"geo" : "马耳他"
}
"time" : 1520697600
}
{
"_id" : ObjectId("5aa63f7034cdbd6928f831ff"),
"domain" : "metacafe.com",
"cdn" : "LLNW",
"geo_bytes" : {
"bytes" : 446,
"geo" : "加拿大"
}
"time" : 1520697600
}
...
然后再用 pipeline 的方式做聚合就好了。