Only fetch categories that are related to a minimum of entries Is there a way to only fetch categories that have been assigned to a minimum of entries, i.e. 4?

Currently I fetch categories like this:

{% set productIds = craft.entries.section('products').ids() %}
{% set categories = craft.categories.relatedTo({ sourceElement: productIds }) %}


I know I can now do the following to only display content for categories which have been assigned to at least  four entries:

{% set entries = craft.entries.section('products').relatedTo(category) %}
{% if entries|length &gt; 4 %}
  ...
{% endif %}


But is there a way to apply this logic to the craft.categories query?
What you can always do in situations, where the default parameters are not enough,
is to "collect" element IDs and pass them to the id param of a new criteria model.

So loop through all categories and merge the category IDs matching you condition to an array:

{% set topCategoriesIds = mainCategoriesIds|merge([category.id]) %}


When you're done, get your filtered categories from these IDs:

{% set categories = craft.categories.id(topCategoriesIds) %}