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

使用MongoDB与JavaScript在投影中统计子文档属性计算未读通知数

MongoDB未读通知统计聚合方案

核心逻辑

针对嵌套的子房间-通知结构,通过两层字段计算实现需求:

  1. 遍历每个子房间的通知列表,过滤出指定用户未读的通知后统计数量
  2. 累加所有子房间的未读数量,得到整个主房间的总未读数

完整聚合查询代码

// 替换以下代码中的"User1"为你要查询的目标用户ID
db.collection.aggregate([
  {
    $addFields: {
      subRoom: {
        $map: {
          input: "$subRoom",
          as: "subRoomItem",
          in: {
            id: "$$subRoomItem.id",
            notRead: {
              $size: {
                $filter: {
                  input: "$$subRoomItem.notifications",
                  as: "notification",
                  cond: {
                    // 判断用户不在read数组中即为未读
                    $not: { $in: ["User1", "$$notification.read"] }
                  }
                }
              }
            }
          }
        }
      }
    }
  },
  {
    $addFields: {
      // 统计所有子房间未读数之和作为主房间总未读
      notRead: { $sum: "$subRoom.notRead" }
    }
  },
  {
    // 投影仅返回需要的字段
    $project: {
      _id: 0,
      room: 1,
      subRoom: 1,
      notRead: 1
    }
  }
])

返回结果说明

以示例数据查询用户User1的未读数据时,返回结果如下:

[
  {
    "notRead": 8,
    "room": "Room1",
    "subRoom": [
      {
        "id": "SubRoom1",
        "notRead": 5
      },
      {
        "id": "SubRoom2",
        "notRead": 3
      }
    ]
  }
]

注:你提供的期望结果中总未读数3应为笔误,若需要特殊的总未读统计规则,可调整第二个$addFields阶段的计算逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 07:57:03