0

I use the Java Spring MongoDB repository in my project.

I have this collection in MongoDB called Info:

{ "_id" : 1, "hosting" : "hostgator.com", count:7 }
{ "_id" : 2, "hosting" : "aws.amazon.com", count:7}
{ "_id" : 3, "hosting" : "aws.amazon.com", count:3}
{ "_id" : 4, "hosting" : "hostgator.com", count:5 }
{ "_id" : 5, "hosting" : "aws.amazon.com", count:1 }
{ "_id" : 6, "hosting" : "cloud.google.com", count:1 }
{ "_id" : 7, "hosting" : "aws.amazon.com", count:5 }
{ "_id" : 8, "hosting" : "hostgator.com", count:2 }
{ "_id" : 9, "hosting" : "cloud.google.com", count:3 }
{ "_id" : 10,"hosting" : "godaddy.com", count:7 }
...
{ "_id" : 100, "hosting" : "godaddy.com", count:5 }

Here is DTO definition:

public class Info{
    public int _id;
    public String hosting;
    public int count;
}

I need to write a query and to get from the database all values of count property and remove the duplications. For example, the result that I expect according to the collection above is:

List<int> counts = [1,2,3,5,7];

For this purpose I use the aggregation group method and MongoTemplate:

        GroupOperation groupOperation = Aggregation.group("count");
        Aggregation aggregation = Aggregation.newAggregation(groupOperation);
        var result = template.aggregate(aggregation, Info.class,  Info[].class);
        System.out.println(result.getMappedResults());

But the result that I get is an empty array - [].

Why I don't get the expected result?

halfer
  • 19,824
  • 17
  • 99
  • 186
Michael
  • 13,950
  • 57
  • 145
  • 288
  • see https://stackoverflow.com/a/46890137/2282634. You should group by hosting and use $first to get a single count. – Joe Mar 11 '21 at 04:12
  • Does this answer your question? [Spring mongodb - group operation after unwind - can not find $first or $push](https://stackoverflow.com/questions/46888425/spring-mongodb-group-operation-after-unwind-can-not-find-first-or-push) – Joe Mar 11 '21 at 04:12
  • 1
    You can try this Spring data query: [How to write a query to get distinct values from mongodb collection?](https://stackoverflow.com/questions/66412093/how-to-write-a-query-to-get-distinct-values-from-mongodb-collection/66423381#66423381) – prasad_ Mar 11 '21 at 05:13
  • @prasad_ amazing! It works perfect thank you! In case if I want to add a filter by some property for example where hosting property-specific value how can i add it to annotation? – Michael Mar 11 '21 at 05:38
  • You can add a `$match` stage before the `$group`. See examples using multiple pipeline stages at [Spring Data MongoDB - @Aggregate](https://docs.spring.io/spring-data/mongodb/docs/3.0.1.RELEASE/api/) . – prasad_ Mar 11 '21 at 05:42

0 Answers0