使用mongo存储库按属性分组

xu3bshqb  于 2021-07-23  发布在  Java
关注(0)|答案(0)|浏览(215)

我在项目中使用JavaSpringMongoDB存储库。
我在mongodb有一个集合叫做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 }

以下是辩护理由:

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

我需要编写一个查询,从数据库中获取count属性的所有值,并删除重复项。
例如,根据上面的集合,我期望的结果是:

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

为此,我使用聚合组方法和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());

但是我得到的结果是一个空数组-[]。
你能帮我回答上面的问题吗?为什么我没有得到预期的结果?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题