You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在NoSQLBooster中关联集合并按指定字段计算平均值

MongoDB 多集合关联分组求平均值

需求说明

现有两个字段结构完全一致的集合,需完成以下操作:

  1. 合并两个集合的所有数据
  2. 分别按energy_products和sub_products字段分组
  3. 对每组的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 05:15:30