Skip to content
Advertisement

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 {

    @Id
    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 }
 ]

Advertisement

Answer

This requirement can also be done logically ..like 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"),
                                                                   Aggregation.sortByCount("bookPublisherName"));
    List<Document> docs=  mongoTemplate.aggregate(aggregation, "documents-bookdata", Document.class).getMappedResults();
          for(Document doc : docs) {
          count = new PublisherBookCount();
              count.setBookPublisherName(doc.get("bookPublisherName").toString());
              count.setBookCount(Integer.parseInt(doc.get("count").toString()));
              list.add(count);
          }
          
          return list;
      }
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement