Skip to content

How to get list of data containing count of a field using Aggregation and Criteria in Spring Boot with MangoDB

Requirement: documents-bookdata collection may have multiple objects with same bookPublisherName but different bookName. Means multiple books can have same publisher so need to extract count of books per publisher .

Model class:

@Document(collection = "documents-bookdata")
public class DocumentsBookdata {

    private String bookId;
    private String bookName;
    private String bookPublisherName;
//setters and getters

Response format pojo

public class PublisherBookCount {

private String bookPublisherName;
private int bookCount;
//setters and getters

Response Format

 { "bookPublisherName": "docClassA", "bookCount": 3023 },
 { "bookPublisherName": "docClassB", "bookCount": 4100 }



This requirement can also be done logically get the list of DocumentsBookdata using findAll and than filter it using loop and store the count for books per publisher.But that would be a lengthy approach.SO below code will simply use Aggregation to get the book cout per publisher

public List<PublisherBookCount> getBookCOunt(){
    List<PendingDocumentCount> list = new ArrayList<>();
    PublisherBookCount count = null;
    Aggregation aggregation = Aggregation.newAggregation( Aggregation.project("bookPublisherName").andExclude("_id"),
    List<Document> docs=  mongoTemplate.aggregate(aggregation, "documents-bookdata", Document.class).getMappedResults();
          for(Document doc : docs) {
          count = new PublisherBookCount();
          return list;
2 People found this is helpful