I have a query and using count based on condition while in java I am using Aggregation GroupOperation Object. so how can write this statement in JAVA? Sample Query :
{
$group: {
_id: {
"categoryCode": "$categoryCode",
"categoryName": "$categoryName"
},
"cat_count": {
$sum: {
$cond: [{ $eq: ["$cat_type", "A"] }, 1, 0]
}
}
}
}
CodePudding user response:
You can use Aggregation classes from org.springframework.data.mongodb.core.aggregation
package to write this query.
ConditionalOperators.Cond cond = ConditionalOperators.Cond.when(ComparisonOperators.Eq.valueOf("$cat_type").equalToValue("A"))
.then(1)
.otherwise(0);
GroupOperation groupOperation = Aggregation.group("categoryCode", "categoryName").sum(cond).as("cat_count");
Now use this groupOperation with mongotemplate to execute query.