MongoDB分组聚合时如何排除含指定元素的结果统计C值?
MongoDB聚合查询新增C指标修改方案
首先先定义你需要排除的salesManagerId数组参数,示例如下:
// 替换为实际需要排除的ID列表 const excludeManagerIds = [ObjectId("60d21b4667d0d8992e610c85"), ObjectId("60d21b4667d0d8992e610c86")]
你只需要在原有聚合的$group阶段新增C指标的统计逻辑即可,修改后的完整聚合语句如下:
db.sales.aggregate([ { $group: { _id: { $dateToString: { format: "%Y-%m-%d", date: "$createdAt" } }, A: { $sum: 1 }, B: { $sum: { $cond: [ { $and: [ { $isArray: "$details" }, { $gt: [{ $size: "$details" }, 0] } ] }, 1, 0 ] } }, // 新增C指标统计逻辑 C: { $sum: { $cond: [ { $and: [ // 先满足B的统计条件:details是有效非空数组 { $isArray: "$details" }, { $gt: [{ $size: "$details" }, 0] }, // 新增排除逻辑:details中所有salesManagerId都不在排除列表中 { $eq: [ { $size: { $setIntersection: [ // 提取details中所有salesManagerId { $map: { input: "$details", in: "$$this.salesManagerId" } }, excludeManagerIds ] } }, 0 ] } ] }, 1, 0 ] } } } }, { $sort: { _id: -1 } } ])
逻辑说明
C指标的判断逻辑完全符合需求:
- 首先过滤掉details为空/不是数组的文档,和B的统计基础一致
- 提取当前文档details下所有salesManagerId,和你指定的排除ID列表求交集
- 如果交集长度为0,说明该文档没有包含要排除的主管ID,计入C指标,否则不计入
如果你的实际数据中确实存在示例里拼写错误的salaesMangerId字段,只需要修改$map的取值逻辑,兼容两种字段名即可:
{ $map: { input: "$details", in: { $ifNull: ["$$this.salesManagerId", "$$this.salaesMangerId"] } } }
内容的提问来源于stack exchange,提问作者newbieeyo
相关产品推荐
相关产品推荐

