MongoDB 从其他集合中获取数组中最常用的类别以及计数

MongoDB get most used categories in array from other collection along with count

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

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

在下面的示例中,类别 245 在 posts 集合中使用了两次,类别 276 使用了一次。输出将根据类别在 posts

中的使用次数对类别进行排名

请注意,post 集合只有类别 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"
    }
  ]
}

Note: This question is not same as so please don't mark is a duplicate.

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

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

Playground