MongoDB内连接与分组统计需求:订单与商品集合聚合查询
MongoDB 按商品标题统计符合条件的订单数据
集合结构
订单(orders)集合
[ { "id": 1, "orderName": "a", "seqId": 100, "etc": [], "desc": [] }, { "id": 2, "orderName": "b", "seqId": 200, "etc": [], "desc": [] }, { "id": 3, "orderName": "c", "seqId": 100 } ]
商品(goods)集合
[ { "id": 1, "title": "example1", "items": [ { "id": 10, "details": [ { "id": 100 }, { "id": 101 } ] }, { "id": 20, "details": [ { "id": 102 }, { "id": 103 } ] } ] }, { "id": 2, "title": "example2", "items": [ { "id": 30, "details": [ { "id": 200 }, { "id": 201 } ] }, { "id": 40, "details": [ { "id": 202 }, { "id": 203 } ] } ] } ]
匹配条件
订单满足以下任一条件即可被纳入统计:
- 订单的
etc和desc数组均为空 - 订单的
etc或desc数组非空,但订单的seqId与商品集合中某条goods.items.details.id的值匹配
统计需求
基于商品集合的title维度统计:
- 每个
title对应的etc和desc数组均为空的订单数量 - 所有符合匹配条件的订单总数量
示例输出格式:
{example1: 1, total: 2} {example2: 1, total: 1}
实现方案
通过MongoDB聚合管道实现,步骤如下:
- 扁平化商品集合的嵌套数组,提取每个标题对应的所有
details.id列表 - 关联订单集合,筛选出符合匹配条件的订单并标记类型
- 按商品标题分组统计对应数据,转换为要求的输出格式
具体聚合查询代码:
db.goods.aggregate([ // 扁平化嵌套数组,提取每个title对应的details.id集合 { $unwind: "$items" }, { $unwind: "$items.details" }, { $group: { _id: "$title", detailIds: { $addToSet: "$items.details.id" }, } }, // 关联orders集合,筛选符合条件的订单并标记类型 { $lookup: { from: "orders", let: { detailIds: "$detailIds" }, pipeline: [ { $match: { $expr: { $or: [ // 条件1:etc和desc均为空数组 { $and: [{ $eq: ["$etc", []] }, { $eq: ["$desc", []] }] }, // 条件2:seqId在detailIds中,且etc/desc非空 { $and: [ { $in: ["$seqId", "$$detailIds"] }, { $or: [{ $ne: ["$etc", []] }, { $ne: ["$desc", []] }] } ] } ] } } }, { $addFields: { isEmptyType: { $and: [{ $eq: ["$etc", []] }, { $eq: ["$desc", []] }] } } } ], as: "matchedOrders" } }, // 统计空数组订单数和总符合数 { $project: { _id: 0, title: "$_id", emptyCount: { $size: { $filter: { input: "$matchedOrders", cond: "$$this.isEmptyType" } } }, totalCount: { $size: "$matchedOrders" } } }, // 转换为目标输出格式 { $replaceRoot: { newRoot: { $mergeObjects: [ { $arrayToObject: [[{ k: "$title", v: "$emptyCount" }]] }, { total: "$totalCount" } ] } } } ])
执行上述查询后,即可得到符合要求的统计结果。
内容的提问来源于stack exchange,提问作者newbieeyo
相关产品推荐
相关产品推荐

