对mongodb 字段中的列表进行查询统计,在日常过程中,需要对mongdb 的字段中为列表的数据进行查询 。mongodb 字段类型为list 中的包含的数据进行统计。
{
"_id" : "bd2984a2246af9245c22db1fe7511d80",
"CorrectwordAll" : [
{
"word" : "下功夫(工)",
"counts" : 44
},
{
"word" : "奋斗终身(生)",
"counts" : 7
},
{
"word" : "座落(坐)",
"counts" : 6
},
{
"word" : "雪中送碳(炭)",
"counts" : 1
},
{
"word" : "心心相应(印)",
"counts" : 1
},
{
"word" : "永保青春(葆)",
"counts" : 1
},
{
"word" : "山青水秀(清)",
"counts" : 1
}
],
"SencewordAll" : [
{
"word" : "隆重召开",
"counts" : 54
},
{
"word" : "下功夫",
"counts" : 44
},
{
"word" : "亲自",
"counts" : 32
},
{
"word" : "军民融合",
"counts" : 15
},
{
"word" : "村官",
"counts" : 9
},
{
"word" : "致词",
"counts" : 8
},
{
"word" : "签定",
"counts" : 7
},
{
"word" : "受权",
"counts" : 5
}
],
"allowed_domains" : [
"xxx.edu.cn"
],
"crawled" : "on",
"create_ts" : ISODate("2021-01-09T20:41:53.321Z"),
"disallowd_domains" : [],
"domains" : "xxx.edu.cn",
"start_urls" : "http://www.xxx.edu.cn/",
"update_ts" : ISODate("2021-01-11T11:56:22.083Z"),
"webname" : "大学",
"status_code" : [
{
"status_code" : "-1",
"counts" : 161,
"status_text" : "附件下载"
},
{
"status_code" : "-99",
"counts" : 67,
"status_text" : "无效链接"
},
{
"status_code" : "200",
"counts" : 5106,
"status_text" : "正常"
},
{
"status_code" : "404",
"counts" : 188,
"status_text" : "死链"
}
],
"tasks" : [
{
"status" : "False",
"counts" : 13868,
"status_text" : "False"
},
{
"status" : "True",
"counts" : 5522,
"status_text" : "True"
}
]
}
这个是文档的内容
现在需要对文档中的tasks的状态进行分类汇总。类似于的sql 语句
select sum(tasks.counts) as result ,tasks.status as type from document group by tasks.status
其实是一个很简单基本的汇总统计。但是由于tasks.status 是列表中的值,暂时无法在mongodb 直接统计。
所以需要对结果重新进行重构。也就是类型sql中的子查询的方式。生成临时中间表的形式进行二次的查询 。
首先:采用 unwind 进行list 列表的解析。
第二步:进行相应的过滤,用match可以减少数据量,提高查询性能
第三步:是重构表格。
第四步:进行数据的统计,汇总等
最终的查询脚本如下:
db.website.aggregate([
{
//解析list
$unwind: "$tasks"
},
{
//去掉无效数据 进行数据过滤
$match: {
"$and": [{
"tasks.status": {
$ne: []
}
}, {
"tasks.status": {
$ne: 0
}
}]
}
},
{
//重构表格
$project: {
_id: 0,
type: "$tasks.status",
// 将tasks.status 转换成 别名 type 类似SQL中的AS别名
result: {
// 将tasks.counts 转换成 别名 result
$cond: {
//判断配型 数组取长度 数字取值
if : {
$eq: [{
"$type": "$tasks.counts"
}, "array"]
},
then: {
"$size": "$tasks.counts"
},
else : "$tasks.counts"
}
}
}
},
{
//按照type统计求合
$group: {
_id: "$type",
count: {
$sum: "$result" //对应上方重构后的数据别名,进行统计
}
}
}
])