0

I have mongo documents roughly like

{
    "_id": {
              "$oid": "243234"
    },
    "category": ["cat1", "cat2"]
}

want to get the count of all the category, (i.e, cat1 = 20, cat2 = 7)
Numbers 20 and 7 are the number of documents where the category list contains respective elements.

Tried aggregation in mongoTemplate which I don't quite get the required projected result.

The projection model:

public class CountModel{
    private String category;
    private Integer count;
}

The code I have tried:

GroupOperation categoryGroup = group("category").count().as("categoryCount");

ProjectionOperation projectionToModel = project()
   .andExpression("category").as("category")
   .andExpression("categoryCount").as("count");

Aggregation aggregation = newAggregation(categoryGroup, matchOperation, projectionToModel);

AggregationResults<PIICategoryCount> results = mongoTemplate.aggregate(aggregation,
   "repo_name",
    CountModel.class);
return results.getMappedResults();

2 Answers 2

1
     db.collection.aggregate([ {$unwind:"$category"}   , { $group:{ _id:"$category" , count: { $sum:1}}   } ])
Sign up to request clarification or add additional context in comments.

Comments

1

Thank you @kiko075 for the answer.

Just giving the answer in spring boot acceptable form.


// unwinds the document(have each document for each element in the list)
UnwindOperation unwindOperation = Aggregation.unwind("category");

// groups by the category which was unwound and counted
GroupOperation categoryGroup = Aggregation.group("category").count().as("categoryCount");

ProjectionOperation projectionToModel = project()
                    .andExpression("_id").as("category")         // _id refers to the unwound category (i.e, cat1)
                    .andExpression("categoryCount").as("count");

Aggregation aggregation = Aggregation.newAggregation(unwindOperation, categoryGroup, projectionToModel);

AggregationResults<CountModel> results = mongoTemplate.aggregate(aggregation,
                    "repo_name",
                    CountModel.class);
return results.getMappedResults();

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.