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

MongoDB聚合Lookup时如何过滤is_deleted为true的关联作者数据?

解决MongoDB聚合查询中过滤已删除作者的问题

你可以通过两种方式实现只保留is_deleted为false的作者:

方法一:关联时直接过滤(推荐,效率更高)

在$lookup中使用pipeline参数,关联author表时就筛选出未删除的作者,避免后续再处理冗余数据:

db.documents.aggregate([
    {
        $lookup: {
            from: "author",
            let: { doc_author_ids: "$author_id" },
            pipeline: [
                {
                    $match: {
                        $expr: {
                            $and: [
                                { $in: ["$_id", "$$doc_author_ids"] },
                                { $eq: ["$is_deleted", false] }
                            ]
                        }
                    }
                }
            ],
            as: "author"
        }
    },
    {
        $project: {
            author_id: 0
        }
    },
    { $skip: 0 },
    { $limit: 2 }
])

这种方式在关联阶段就过滤掉已删除的作者,减少数据传输和后续处理的开销。

方法二:关联后过滤数组

如果需要先获取所有关联作者再做过滤,可以在$lookup之后使用$filter操作符处理author数组:

db.documents.aggregate([
    {
        $lookup: {
            from: "author",
            localField: "author_id",
            foreignField: "_id",
            as: "author"
        }
    },
    {
        $addFields: {
            author: {
                $filter: {
                    input: "$author",
                    cond: { $eq: ["$$this.is_deleted", false] }
                }
            }
        }
    },
    {
        $project: {
            author_id: 0
        }
    },
    { $skip: 0 },
    { $limit: 2 }
])

这里通过$addFields替换原有的author数组,只保留is_deleted为false的元素。

内容的提问来源于stack exchange,提问作者B18DCCN424 - Lê Khắc Nam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 12:59:14