【问题标题】:MongoDB get most used categories in array from other collection along with countMongoDB 从其他集合中获取数组中最常用的类别以及计数
【发布时间】:2021-10-01 01:14:18
【问题描述】:

这是我尝试过的一个 mongodb 游乐场 - https://mongoplayground.net/p/_rjZo8aak6b

在此示例中,我在 Array 中按顺序获取顶级类别,但我还需要包含出现次数的对象数组。

在下面的示例中,类别 245 在帖子集合中使用了两次,而 276 则使用了一次。输出将根据帖子中的使用次数对类别进行排名

请注意,帖子集合只有类别 ID,因此需要查找类别集合。

预期结果是:

{
  topCategories: [{name: "category 245", count: 2},{name: "category 276", count: 1}]
}

样本数据如下:

db={
  categories: [
    {
      "_id": 231,
      "text": "category 231"
    },
    {
      "_id": 276,
      "text": "category 276"
    },
    {
      "_id": 245,
      "text": "category 245"
    }
  ],
  posts: [
    {
      "_id": 74,
      category: "245"
    },
    {
      "_id": 75,
      category: "245"
    },
    {
      "_id": 72,
      category: "276"
    }
  ]
}

注意:这个问题与 mongodb - get top items from a collection based on its usage count as a field in another collection 所以请不要标记是重复的。

【问题讨论】:

    标签: mongodb mongoose aggregation-framework aggregate aggregate-functions


    【解决方案1】:

    只需要修正最后一个$group阶段,

    • 创建name属性来设置第一类text
    • 创建count 属性并设置计数
      {
        $group: {
          _id: null,
          topCategories: {
            $push: {
              name: { $arrayElemAt: ["$category.text", 0] },
              count: "$count"
            }
          }
        }
      }
    

    Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-02
      • 1970-01-01
      • 2014-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-09
      相关资源
      最近更新 更多