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

基于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 } }
])

代码说明

  1. $match:先筛选出所有postType为"buy"的记录,减少后续聚合操作的数据量,提升效率。
  2. $group:以product为分组键,用$sum:1统计每个产品的购买次数,结果存入count字段。
  3. $sort:按照count字段降序排列,确保购买次数多的产品排在前列。
  4. $limit:限制结果仅返回前10条,得到Top10热门购买产品。
  5. $project:调整输出结构,将分组用的_id字段重命名为product,并移除原_id字段,让输出符合预期格式。

无效代码问题说明

$setEquals是MongoDB中用于比较两个集合是否完全相等的操作符,用它判断单个字段postType是否等于"buy"属于逻辑错误,无法实现过滤和统计需求。正确做法是用$match过滤目标记录,再通过后续聚合步骤完成统计排序。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 07:00:58