MongoDB聚合:嵌套对象反向$Unwind及评论数据过滤方案
MongoDB聚合查询:过滤嵌套评论并清理无效用户条目
需求回顾
- 过滤掉
isDeleted: true或suspended: true的评论条目 - 若用户所有评论均无效,则移除该用户的评论信息
- 保留原数据结构
聚合查询语句
db.collection.aggregate([ { $set: { review: { $map: { input: "$review", as: "userReview", in: { user: "$$userReview.user", reviewArray: { $filter: { input: "$$userReview.reviewArray", cond: { $and: [ { $eq: ["$$this.isDeleted", false] }, { $eq: ["$$this.suspended", false] } ] } } } } } } } }, { $set: { review: { $filter: { input: "$review", cond: { $gt: [{ $size: "$$this.reviewArray" }, 0] } } } } } ])
步骤说明
第一层过滤:清理单用户下的无效评论
- 通过
$map遍历每个业务的用户评论列表,对每个用户的reviewArray使用$filter,仅保留isDeleted和suspended均为false的有效评论 - 保留用户ID与过滤后的有效评论数组
- 通过
第二层过滤:移除无有效评论的用户
- 再次对业务的
review数组做$filter,只保留reviewArray长度大于0的用户条目(即该用户至少有一条有效评论) - 最终输出结构与原数据一致,仅剔除无效内容
- 再次对业务的
内容的提问来源于stack exchange,提问作者rajiv dahal
相关产品推荐
相关产品推荐

