基于postType=buy的MongoDB分组查询:生成Top10产品列表
需求:生成postType为"buy"的Top10产品统计列表
需要从logs集合中统计postType="buy"的记录,按产品分组计数,排序后取前10个产品。
示例日志集合
[ { "_id": "633dc5b761ff04e7ae8e8c0f", "postType": "buy", "product": "3" }, { "_id": "633dc5b761ff04e7ae8e8c0f", "postType": "view", "product": "4" }, { "_id": "633dc5b761ff04e7ae8e8c0f", "postType": "buy", "product": "2" }, { "_id": "633dc5b761ff04e7ae8e8c0f", "postType": "view", "product": "2" }, { "_id": "633dc5b761ff04e7ae8e8c0f", "postType": "share", "product": "3" }, { "_id": "633dc5b761ff04e7ae8e8c0f", "postType": "buy", "product": "2" }, { "_id": "633dc5b761ff04e7ae8e8c0f", "postType": "buy", "product": "2" }, { "_id": "633dc5b761ff04e7ae8e8c0f", "postType": "share", "product": "2" }, { "_id": "633dc5b761ff04e7ae8e8c0f", "postType": "buy", "product": "1" }, { "_id": "633dc5b761ff04e7ae8e8c0f", "postType": "buy", "product": "1" }, { "_id": "633dc5b761ff04e7ae8e8c0f", "postType": "viewvideo", "product": "1" }, { "_id": "633dc5b761ff04e7ae8e8c0f", "postType": "viewvideo", "product": "2" }, { "_id": "633dc5b761ff04e7ae8e8c0f", "postType": "viewvideo", "product": "3" }, { "_id": "633dc5b761ff04e7ae8e8c0f", "postType": "buy", "product": "4" }, { "_id": "633dc5b761ff04e7ae8e8c0f", "postType": "buy", "product": "5" } ]
预期输出
[ {"product": "1", "count": 2}, {"product": "2", "count": 3}, {"product": "3", "count": 1}, {"product": "4", "count": 1}, {"product": "5", "count": 1} ]
尝试的无效代码
{ $project: { _id: 0, list: { $setEquals: ["$postType", "buy"] } } }
正确的聚合查询代码
db.logs.aggregate([ // 过滤出postType为buy的记录 { $match: { postType: "buy" } }, // 按product分组,统计每组的购买次数 { $group: { _id: "$product", count: { $sum: 1 } } }, // 按购买次数降序排序 { $sort: { count: -1 } }, // 取前10条结果 { $limit: 10 }, // 调整输出格式,将_id重命名为product { $project: { _id: 0, product: "$_id", count: 1 } } ])
代码说明
- $match:先筛选出所有
postType为"buy"的记录,减少后续聚合操作的数据量,提升效率。 - $group:以
product为分组键,用$sum:1统计每个产品的购买次数,结果存入count字段。 - $sort:按照
count字段降序排列,确保购买次数多的产品排在前列。 - $limit:限制结果仅返回前10条,得到Top10热门购买产品。
- $project:调整输出结构,将分组用的
_id字段重命名为product,并移除原_id字段,让输出符合预期格式。
无效代码问题说明
$setEquals是MongoDB中用于比较两个集合是否完全相等的操作符,用它判断单个字段postType是否等于"buy"属于逻辑错误,无法实现过滤和统计需求。正确做法是用$match过滤目标记录,再通过后续聚合步骤完成统计排序。
内容的提问来源于stack exchange,提问作者Rezaul karim
相关产品推荐
相关产品推荐

