Armen Arzumanyan
Armen Arzumanyan

Reputation: 2043

mongodb 3 java: aggregation sum of keys

I have collection which is have _id and searchKey . I want to know count of each stored key like "java 2, C++ 3 " . My entity is

public class SearchKeyModel implements Serializable {

    private static final long serialVersionUID = 2099119595418807689L;

    private String searchKey;
    private Integer count;  

Aggregation like this:

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());

But sortedList.hasNext() always false.

Can anyone help to understand how to finish this?

Upvotes: 0

Views: 2143

Answers (1)

s7vr
s7vr

Reputation: 75934

You can try below aggregation to get the desired result.

Added $project stage to get the output with the same key names as java class fields name for Gson to map them correctly.

I have also changed query to use static helper method.

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();

Upvotes: 2

Related Questions