如何在NoSQLBooster中关联集合并按指定字段计算平均值
MongoDB 多集合关联分组求平均值
需求说明
现有两个字段结构完全一致的集合,需完成以下操作:
- 合并两个集合的所有数据
- 分别按
energy_products和sub_products字段分组 - 对每组的
value_ktoe字段计算平均值并输出
集合文档示例
集合1文档
{ "_id" : ObjectId("63074885ff3acbe0d63d7686"), "year" : "2020", "energy_products" : "Other Energy Products", "sub_products" : "Other Energy Products", "value_ktoe" : "70.4" }
集合2文档
{ "_id" : ObjectId("63074882ff3acbe0d63c391a"), "year" : "2020", "energy_products" : "Petroleum Products", "sub_products" : "Other Petroleum Products", "value_ktoe" : "10633.7" }
解决方案
使用MongoDB聚合管道实现,核心逻辑:合并集合数据→转换数值类型→并行处理两种分组统计→整理输出格式。
聚合查询代码
假设两个集合名为collectionA和collectionB,执行以下命令:
db.collectionA.aggregate([ // 合并两个集合的数据 { $unionWith: { coll: "collectionB" } }, // 将字符串类型的value_ktoe转为数值,否则无法计算平均值 { $project: { energy_products: 1, sub_products: 1, value_ktoe: { $toDouble: "$value_ktoe" } } }, // 同时处理两种分组统计逻辑 { $facet: { by_energy_product: [ { $group: { _id: { energy_products: "$energy_products" }, avg: { $avg: "$value_ktoe" } } } ], by_sub_product: [ { $group: { _id: { sub_products: "$sub_products" }, avg: { $avg: "$value_ktoe" } } } ] } }, // 合并两组统计结果并展开为单个文档 { $project: { combined: { $concatArrays: ["$by_energy_product", "$by_sub_product"] } } }, { $unwind: "$combined" }, { $replaceRoot: { newRoot: "$combined" } } ])
预期输出
{ "_id" : { "energy_products" : "Petroleum Products" }, "avg" : 18312.05625 }
{ "_id" : { "sub_products" : "Jet Fuel Kerosene" }, "avg" : 4253.884375 }
内容的提问来源于stack exchange,提问作者Charan Lime stone
相关产品推荐
相关产品推荐

