Like what we’re doing? Star us on GitHub!

Is it possible to count posts/pages by group by a category field?

Stupidism
3 months ago
2 2

I have a tab switch to show two different categories of articles with the total num shown in tab title.

https://getjerry.com/data-and-studies

image

Now I'm using two queries to fetch these two counts separately.

countStudies: Articles(
    where: {
      category: { equals: "studies" }
      slug: { not_in: $excludeSlugs }
      noCard: { not_equals: true }
      _status: $_status
    }
    page: $page
    limit: $limit
    sort: "-publishDate"
  ) {
    totalDocs
  }
  countTrendsReports: Articles(
    where: {
      category: { equals: "trends-reports" }
      slug: { not_in: $excludeSlugs }
      noCard: { not_equals: true }
      _status: $_status
    }
    page: $page
    limit: $limit
    sort: "-publishDate"
  ) {
    totalDocs
  }

It works, but I'm wondering if there's a more elegant(one query) or extensible(if I need all categories) way to do this.

  • jacobsfletch
    Payload Team
    2 months ago

    @Stupidism there's currently no API for this, however, you could wire up your own custom endpoint to consolidate multiple queries. It would look like this: your front-end makes a single request to your Payload server, it uses the Local API to query "studies" and "trend reports" similarly to your example above, then it returns both results back to you in a single response.

    @ChrisGV04 I think what you're talking about to is slightly different, although a great idea. This is already some discussion around bidirectional/inversed relationships, check it out!

    1 reply
  • ChrisGV04
    2 months ago

    @jacobsfletch That's right. The solution I proposed is the way I have seen that some other CMS manage it, but I understand it's a different topic.

    However your proposed solution is a good option. I personally use MongoDB aggregations in a custom route to perform these counts.

    Great work on Payload btw! My favorite CMS by far

  • ChrisGV04
    3 months ago

    I'm having the exact same situation. The only thing I could think of was if there was some sort of bi-directional field in the relationship between the collections. For example: In the Articles collection there's a category field and on the Category collection there's a articles field with hasMany: true.

    Other CMS like Strapi and Directus handle this with the "one-to-one", "one-to-many" and "many-to-many" technique, which automatically maintains both fields I mentioned before as a nice relationship. However, I imagine that it's easier on those CMS because they use SQL databases but Payload uses MongoDB that's NoSQL.

Open the post
Continue the discussion in GitHub
Can't find what you're looking for?
Get help straight from the Payload team with an Enterprise License.Learn More