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

如何在AWS DocumentDB中实现左外连接并统计租户数量?

AWS DocumentDB实现按所有者统计租户数量的解决方案

原MongoDB中使用localField/foreignField简化版$lookup的语句在AWS DocumentDB中会抛出invalid $lookup namespace错误,这是因为DocumentDB对该简化语法的支持存在限制,改用管道式$lookup即可解决问题,具体实现语句如下:

db.owner_collection.aggregate([
  // 关联租户集合并统计数量
  {
    $lookup: {
      from: "tenant_collection",
      let: { current_owner_id: "$_id" },
      pipeline: [
        { $match: { $expr: { $eq: ["$owner_id", "$$current_owner_id"] } } },
        { $count: "total" }
      ],
      as: "tenant_stats"
    }
  },
  // 提取统计数值,无租户时设为0
  {
    $addFields: {
      tenantCount: {
        $ifNull: [{ $arrayElemAt: ["$tenant_stats.total", 0] }, 0]
      }
    }
  },
  // 保留需要的字段
  {
    $project: {
      _id: 1,
      owner_name: 1,
      tenantCount: 1
    }
  }
])

逻辑说明

  1. let与管道匹配:通过let定义变量传递当前所有者的_id,在pipeline内用$expr+$eq实现跨集合的ID匹配,避免简化语法的兼容性问题。
  2. 内置统计:在lookup的管道中直接用$count统计匹配到的租户数量,减少后续处理步骤。
  3. 空值处理:用$arrayElemAt提取统计结果数组中的数值,结合$ifNull确保没有租户的所有者统计值为0。

预期输出

执行后会得到每个所有者对应的租户数量:

[
  { "_id": ObjectId("123dddfffaaa7744"), "owner_name": "Sam", "tenantCount": 3 },
  { "_id": ObjectId("243dddfffaaa7755"), "owner_name": "Ray", "tenantCount": 1 }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 01:25:37