如何在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 } } ])
逻辑说明
let与管道匹配:通过let定义变量传递当前所有者的_id,在pipeline内用$expr+$eq实现跨集合的ID匹配,避免简化语法的兼容性问题。- 内置统计:在lookup的管道中直接用
$count统计匹配到的租户数量,减少后续处理步骤。 - 空值处理:用
$arrayElemAt提取统计结果数组中的数值,结合$ifNull确保没有租户的所有者统计值为0。
预期输出
执行后会得到每个所有者对应的租户数量:
[ { "_id": ObjectId("123dddfffaaa7744"), "owner_name": "Sam", "tenantCount": 3 }, { "_id": ObjectId("243dddfffaaa7755"), "owner_name": "Ray", "tenantCount": 1 } ]
内容的提问来源于stack exchange,提问作者uday214125
相关产品推荐
相关产品推荐

