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
相关产品推荐
相关产品推荐

