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

MongoDB查询中$replaceRoot正确用法 调整关联查询输出结构

问题原因

你当前的输出多了detail嵌套层,是因为$replaceRoot阶段的$mergeObjects参数写法错误:你把包含公司原生数据的detail对象作为了新根的一个键值对{detail: "$detail"}传入,而没有直接展开detail内部的字段。

解决方案

只需要修改$replaceRoot阶段的$mergeObjects参数即可,修改后的完整聚合语句如下:

db.companyentities.aggregate([
    {
        $unwind: "$productIds"
    },
    {
        $lookup: {
            as: "products",
            foreignField: "_id",
            from: "productentities",
            localField: "productIds"
        }
    },
    {
        $unwind: "$products"
    },
    {
        $lookup: {
            as: "products.productCategory",
            foreignField: "_id",
            from: "productcategoryentities",
            localField: "products.productCategoryId"
        }
    },
    {
        $unwind: "$products.productCategory"
    },
    {
        $group: {
            _id: "$_id",
            products: {
                $push: "$products"
            },
            detail: {
                $first: "$$ROOT"
            }
        }
    },
    {
        $replaceRoot: {
            newRoot: {
                $mergeObjects: [
                    "$detail", // 直接传入detail对象,展开所有公司原生字段到根层级
                    {products: "$products"} // 用聚合好的商品数组覆盖detail中临时的单个product字段
                ]
            }
        }
    }
])

补充说明

如果你需要保留没有关联产品的公司数据,可以在第一个$unwind阶段添加preserveNullAndEmptyArrays: true配置,避免空productIds的公司被过滤:

{
    $unwind: {
        path: "$productIds",
        preserveNullAndEmptyArrays: true
    }
}

内容的提问来源于stack exchange,提问作者DeineOma420

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 04:54:05