mongodb 3 java:键的聚合和

mongodb 3 java: aggregation sum of keys

我有一个包含 _id 和 searchKey 的集合。我想知道每个存储密钥的计数,例如 "java 2, C++ 3 " 。 我的实体是

public class SearchKeyModel implements Serializable {

    private static final long serialVersionUID = 2099119595418807689L;

    private String searchKey;
    private Integer count;  

像这样聚合:

Iterator<Document> sortedList = collection
            .aggregate(Arrays.asList(new Document("$match", new Document("searchKey", 1)),
                    new Document("$sort", new Document("count", -1)),
                    new Document("$group", new Document("_id", null).append("count", new Document("$sum", 1)
                    ))
            )).iterator();

    System.out.println("list hasNext " + sortedList.hasNext());

    while (sortedList.hasNext()) {
        Document doc = sortedList.next();
        SearchKeyModel entity = gson.fromJson(doc.toJson(), SearchKeyModel.class);
        list.add(entity);
    }
        System.out.println("list size is " + list.size());

但是 sortedList.hasNext() 总是错误的。

任何人都可以帮助理解如何完成这个吗?

您可以尝试以下聚合以获得所需的结果。

添加了 $project 阶段以获取与 java class 字段名称相同的键名称的输出,以便 Gson 正确映射它们。

我还更改了查询以使用静态辅助方法。

List<Bson> aggregation = Arrays.asList(
                Aggregates.group("$searchKey", Accumulators.sum("count", 1)),
                Aggregates.sort(Sorts.descending("count")),
                Aggregates.project(Projections.fields(Projections.excludeId(), Projections.computed("searchKey", "$_id"), Projections.include("count"))));

 Iterator<Document> sortedList = collection.aggregate(aggregation).iterator();