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

Viewed 141

Here is a mongodb playground which I tried - https://mongoplayground.net/p/_rjZo8aak6b

In this example I am getting top categories order wise in Array but I also need array of object which contains occurrence count also.

In the example below, category 245 is used twice and 276 is used once in the posts collection. The output will rank the categories based on their count of usage in posts

Note that the post collection only has the category id so looking up categories collection is necessary.

Expected result is:

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

Sample data is as below:

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 mongodb - get top items from a collection based on its usage count as a field in another collection so please don't mark is a duplicate.

1 Answers

Just need to correct last $group stage,

  • create name property to set first category text
  • create count property and set count
  {
    $group: {
      _id: null,
      topCategories: {
        $push: {
          name: { $arrayElemAt: ["$category.text", 0] },
          count: "$count"
        }
      }
    }
  }

Playground

Related