MongoDB聚合查询求助:筛选新加坡人口±10%国家的排放数据
MongoDB聚合:筛选人口接近新加坡的国家2010-2020年排放数据
你已经算出了新加坡的人口范围,接下来只需将这个范围与原集合数据关联,就能筛选出符合条件的国家并提取排放数据。以下是完整的聚合管道,一步完成所有需求:
[ // 计算新加坡2010-2020年平均人口及±10%范围 { $match: { country: 'Singapore', year: { $gte: '2010', $lte: '2020' } } }, { $group: { _id: null, avgSingaporePop: { $avg: { $convert: { input: '$population', to: 'decimal', onError: 0, onNull: 0 } } } } }, { $addFields: { minPop: { $multiply: ['$avgSingaporePop', 0.9] }, maxPop: { $multiply: ['$avgSingaporePop', 1.1] } } }, // 关联原集合筛选符合条件的国家 { $lookup: { from: 'your_collection_name', // 替换为你的实际集合名 let: { min: '$minPop', max: '$maxPop' }, pipeline: [ { $match: { $expr: { $and: [ { $ne: ['$country', 'Singapore'] }, // 排除新加坡本身 { $gte: ['$year', '2010'] }, { $lte: ['$year', '2020'] }, // 人口转换为decimal后在范围内 { $gte: [ { $convert: { input: '$population', to: 'decimal', onError: 0, onNull: 0 } }, '$$min' ] }, { $lte: [ { $convert: { input: '$population', to: 'decimal', onError: 0, onNull: 0 } }, '$$max' ] } ] } } }, // 可选:按国家分组整理年度数据(适合可视化) { $group: { _id: '$country', emissionsTrend: { $push: { year: '$year', emissions: '$emissions', population: '$population' } }, avgAnnualEmissions: { $avg: '$emissions' } } } ], as: 'targetCountries' } }, // 展开结果并调整结构 { $unwind: '$targetCountries' }, { $replaceRoot: { newRoot: '$targetCountries' } } ]
关键步骤说明:
- 计算新加坡人口范围:和你之前的逻辑一致,但将
_id设为null,确保只生成一条汇总记录,方便后续关联。 - $lookup关联筛选:通过
let传递人口上下限参数,在子管道里匹配其他国家的符合条件的数据:- 排除新加坡本身,避免重复
- 限定年份在2010-2020
- 把人口转换为decimal类型后,判断是否在±10%范围内
- 数据整理(可选):子管道里的
$group会把每个国家的年度数据打包成数组,同时计算平均排放,这样的结构更适合做趋势可视化。如果需要原始的单年度记录,直接去掉这个$group步骤即可。
示例输出结构:
{ "_id": "某个符合条件的国家", "emissionsTrend": [ { "year": "2010", "emissions": 1234, "population": 5000000 }, { "year": "2011", "emissions": 1300, "population": 5050000 }, // ... 2012-2020年数据 ], "avgAnnualEmissions": 1500 }
内容的提问来源于stack exchange,提问作者Gerald
相关产品推荐
相关产品推荐

