如何在MongoDB中删除深度嵌套对象数组内指定ID的评论
解决方案
核心问题说明
你之前使用的find/findById是查询类方法,findOneAndRemove/findOneAndDelete是删除整个顶层文档的方法,而你的需求是更新顶层公告文档,删除其内部嵌套数组里的指定评论子元素,因此需要用更新类方法实现。
方案1:固定嵌套层数实现(适配你给出的示例结构)
你示例中的目标评论嵌套在4层comments数组中,可以直接用arrayFilters匹配所有层级的嵌套数组,执行移除操作:
const announcementId = "60aa8ed98ad79d380cb250b4"; // 顶层公告ID const targetCommentId = "60aa912b301ccc397057ded6"; // 要删除的评论ID await AnnouncementModel.findOneAndUpdate( { _id: announcementId }, { $pull: { "comments.$[level1].comments.$[level2].comments.$[level3].comments": { _id: targetCommentId } } }, { arrayFilters: [ { "level1._id": { $exists: true } }, { "level2._id": { $exists: true } }, { "level3._id": { $exists: true } } ], new: true // 返回更新后的文档 } );
方案2:通用无限层级嵌套实现(适配任意深度的回复嵌套)
如果你的评论支持任意层级的嵌套回复,不需要固定层数,可以用MongoDB 4.4及以上版本支持的聚合管道更新,配合递归函数过滤所有层级的评论:
const announcementId = "60aa8ed98ad79d380cb250b4"; // 如果_id是ObjectId类型,需要先转换:const targetCommentId = mongoose.Types.ObjectId("60aa912b301ccc397057ded6") const targetCommentId = "60aa912b301ccc397057ded6"; await AnnouncementModel.findOneAndUpdate( { _id: announcementId }, [ { $set: { comments: { $function: { body: function filterComments(comments, targetId) { // 递归过滤所有层级的评论 return comments.filter(comment => { // 先递归过滤当前评论的子评论 if (comment.comments && comment.comments.length > 0) { comment.comments = filterComments(comment.comments, targetId); } // 排除ID匹配的评论 return comment._id != targetId; }); }, args: ["$comments", targetCommentId], lang: "js" } } } } ], { new: true } );
内容的提问来源于stack exchange,提问作者Sandeep Anumalla
相关产品推荐
相关产品推荐

