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

MongoDB同集合按addedBy分组并按propertyType聚合文档

MongoDB 按用户分组并分类汇总房产数据

聚合管道解决方案

无需使用$lookup,直接通过$group结合条件判断就能实现需求,以下是完整的聚合管道代码:

db.properties.aggregate([
  // 按addedBy分组,分类收集房产文档
  {
    $group: {
      _id: "$addedBy",
      flats: {
        $push: {
          $cond: [{ $eq: ["$propertyType", "flats"] }, "$$ROOT", "$$REMOVE"]
        }
      },
      banglows: {
        $push: {
          $cond: [{ $eq: ["$propertyType", "banglows"] }, "$$ROOT", "$$REMOVE"]
        }
      },
      totalProperties: { $sum: 1 }
    }
  },
  // 过滤数组中的空值,优化输出格式
  {
    $project: {
      _id: 0,
      addedBy: "$_id",
      flats: { $filter: { input: "$flats", cond: { $ne: ["$$this", null] } } },
      banglows: { $filter: { input: "$banglows", cond: { $ne: ["$$this", null] } } },
      totalProperties: 1
    }
  }
])

代码说明

  • $group阶段:
    • 以addedBy为分组依据,用$cond判断房产类型,将符合条件的完整文档分别推入flats和banglows数组;不符合的返回$$REMOVE标记
    • 同时统计该用户添加的房产总数totalProperties
  • $project阶段:
    • 将分组的_id重命名为addedBy,让输出更直观
    • 用$filter移除数组中的空值,确保用户没有某类房产时对应数组为空,而非包含null

示例输出格式

[
  {
    "addedBy": "user123",
    "flats": [
      { "_id": ObjectId("..."), "propertyType": "flats", "addedBy": "user123", ... },
      { "_id": ObjectId("..."), "propertyType": "flats", "addedBy": "user123", ... }
    ],
    "banglows": [
      { "_id": ObjectId("..."), "propertyType": "banglows", "addedBy": "user123", ... }
    ],
    "totalProperties": 3
  },
  {
    "addedBy": "user456",
    "flats": [],
    "banglows": [
      { "_id": ObjectId("..."), "propertyType": "banglows", "addedBy": "user456", ... }
    ],
    "totalProperties": 1
  }
]

如果仅需统计各类房产数量而非收集完整文档,可将$push替换为$sum:

{
  $group: {
    _id: "$addedBy",
    flatCount: {
      $sum: { $cond: [{ $eq: ["$propertyType", "flats"] }, 1, 0] }
    },
    banglowCount: {
      $sum: { $cond: [{ $eq: ["$propertyType", "banglows"] }, 1, 0] }
    },
    totalProperties: { $sum: 1 }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 15:07:46