I am new in DDD and my understansing of the repository pattern is that it acts like a collection of aggregate roots where you can add, delete, update,etc a certain aggregate root. My question is, where code that performs aggregate functions (count, group by, sum, etc), should be placed, since it does not return or operate over an aggregate root? Thanks

  • In the aggregate's repository. Yes.
    – Euphoric
    Aug 31, 2016 at 4:18
  • Would you mind to explain why please? Aug 31, 2016 at 10:54
  • Why not? I don't see any problem having function in repository that runs query over multiple entities. I actually cannot imagine any other place. Because if you put it anywhere else, it will have to be implemented using persistence-specific code, turning that place into repository.
    – Euphoric
    Aug 31, 2016 at 11:06
  • At least, count is a legit feature of any repository. It would equivalent to size() or length of any collection. For complex aggregates that may change the data model (entity) the repository works with, I agreed with to set another repository. However if what you need is to retrieve reports I'm not sure about repositories as the way to go for such purpose. It may leak on scalability because every timd you need a new report you may need to set a new repository
    – Laiv
    Oct 30, 2016 at 10:17

2 Answers 2


Probably on another aggregate

The fact that you have a need to count certain aggregates indicates that you might be missing a level in your domain model. For example, if you have a 'customer' aggregate root but find yourself having to display the total number of customers, you need some notion in your domain to put that count on. You never just 'count' customers, instead your company has a list of customers and you can count the amount of customers in that list.

That being said, you need to ask yourself the question if the added complexity of introducing another aggregate is worth it. If you only need the number of customers it might be more realistic to simply put the count on your repository. If you find yourself needing a number of counts (get the total number of customers in a pie chart that makes a distinction between customers in your town, in your state, in your country, in your continent and 'other') if might be better to introduce a natural concept in your domain.


I like @JDT's answer.

However, if you decide to just add methods to your repository and you find that the repository is getting bloated over time with too many aggregation methods, you can refactor each one into a separate query object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.