- 需求: 统计不同年龄段的人(年龄段不定)
public ResponseEntity query(@PathVariable("db") String dbName) {
List<AggregationOperation> operations = new ArrayList<>();
Fields fields = Fields.fields("info_age");
operations.add(Aggregation.project(fields).and(ConditionalOperators.switchCases(
// 这个switch可以有多组, 此处参数是个数组
ConditionalOperators.Switch.CaseOperator.when(
BooleanOperators.And.and(
ComparisonOperators.Gte.valueOf("info_age").greaterThanEqualToValue(0),
ComparisonOperators.Lte.valueOf("info_age").lessThanEqualToValue(30)
)
).then("0-30岁"),
ConditionalOperators.Switch.CaseOperator.when(
BooleanOperators.And.and(
ComparisonOperators.Gt.valueOf("info_age").greaterThanValue(30),
ComparisonOperators.Lte.valueOf("info_age").lessThanEqualToValue(60)
)
).then("30-60岁"),
ConditionalOperators.Switch.CaseOperator.when(
BooleanOperators.And.and(
ComparisonOperators.Gt.valueOf("info_age").greaterThanValue(60),
ComparisonOperators.Lte.valueOf("info_age").lessThanEqualToValue(100)
)
).then("60-100岁")
).defaultTo("不符合的数据")).as("age"));
operations.add(Aggregation.group("$age").count().as("total"));
Aggregation aggregation = Aggregation.newAggregation(operations);
AggregationResults<Map> results = mongoTemplate.aggregate(aggregation, dbName, Map.class);
List<Map> myList = results.getMappedResults();
// [{_id=不符合的数据, total=6960}, {_id=60-100岁, total=6782}, {_id=0-30岁, total=34731}, {_id=30-60岁, total=47972}]
System.out.println(myList);
return ResponseEntity.success();
}
- 对应的Mongodb查询语句是
db.user.aggregate(
[
{
"$project": {
"info_age": 1,
"_id": 1,
"age": {
"$switch": {
"branches": [
{
"case": {
"$and": [
{
"$gte": [
"$info_age",
0
]
},
{
"$lte": [
"$info_age",
30
]
}
]
},
"then": 1
},
{
"case": {
"$and": [
{
"$gt": [
"$info_age",
30
]
},
{
"$lte": [
"$info_age",
60
]
}
]
},
"then": 2
},
{
"case": {
"$and": [
{
"$gt": [
"$info_age",
60
]
},
{
"$lte": [
"$info_age",
100
]
}
]
},
"then": 3
}
],
"default": "4"
}
}
}
},
{
"$group": {
"_id": "$age",
"total": {
"$sum": 1
}
}
}
]
)
- 返回的结果是
[{_id=不符合的数据, total=6960}, {_id=60-100岁, total=6782}, {_id=0-30岁, total=34731}, {_id=30-60岁, total=47972}]