0

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?

0

1 Answer 1

2

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.