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

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] }
        }
      }
    }
  }
])

步骤说明

  1. 第一层过滤:清理单用户下的无效评论

    • 通过$map遍历每个业务的用户评论列表,对每个用户的reviewArray使用$filter,仅保留isDeleted和suspended均为false的有效评论
    • 保留用户ID与过滤后的有效评论数组
  2. 第二层过滤:移除无有效评论的用户

    • 再次对业务的review数组做$filter,只保留reviewArray长度大于0的用户条目(即该用户至少有一条有效评论)
    • 最终输出结构与原数据一致,仅剔除无效内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 00:55:26