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

MongoDB带lookup的聚合查询嵌套对象数组无评论返回空对象问题

问题原因

你在对$posts.comments执行$unwind时开启了preserveNullAndEmptyArrays: true,当帖子的comments为空数组时,会生成一条posts.comments为null的记录,后续分组时$push操作会把这条空记录存入comments数组,最终导致无评论的帖子返回包含空对象的数组。

解决方案

修改你的聚合查询,在第二个$group阶段构造posts的comments字段时,用$filter过滤掉空的评论元素即可,修改后的完整查询如下:

db.users.aggregate([
    { $unwind: { path: '$posts', preserveNullAndEmptyArrays: true } },
    { $unwind: { path: '$posts.comments', preserveNullAndEmptyArrays: true } },
    {
        $lookup: {
            from: 'users',
            localField: 'posts.comments.createdBy',
            foreignField: '_id',
            as: 'posts.comments.createdBy'
        }
    },
    { $unwind: { path: '$posts.comments.createdBy', preserveNullAndEmptyArrays: true } },
    {
        $group: {
            _id: { _id: '$_id', post_id: '$posts._id' },
            name: { $first: '$name' },
            posts: { $first: '$posts' },
            comments: { $push: '$posts.comments' },
        }
    },
    {
        $group: {
            _id: '$_id._id',
            name: { $first: '$name' },
            posts: {
                $push: {
                    _id: '$_id.post_id',
                    date: '$posts.date',
                    content: '$posts.content',
                    // 过滤掉没有_id的空评论
                    comments: {
                        $filter: {
                            input: '$comments',
                            as: 'comment',
                            cond: { $ne: [ '$$comment._id', null ] }
                        }
                    }
                }
            }
        }
    },
])

如果需要更严谨的过滤,也可以把判断条件替换为{ $exists: [ '$$comment._id', true ] },确保只保留有效评论。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 12:27:07