聚合查询
根据source分组统计个数
[
{
$group: {
_id: "$source",
total: {
$sum: 1
}
}
},
{
$sort: {
total: -1
}
}
]
GroupOperation operation = Aggregation.group("source").count().as("total");
// 排序
SortOperation sortOperation = Aggregation.sort(Sort.Direction.DESC,"total");
Aggregation aggregation = Aggregation.newAggregation(operation,sortOperation);
AggregationResults<Map> result = mongoTemplate.aggregate(aggregation,"base_info", Map.class);
// 获取结果
result.getMappedResults()
根据source,language和分组统计个数
[
{
$group: {
_id:{
source:"$source",
language:"$language"
},
total: {
$sum: 1
}
},
}
]
GroupOperation operation = Aggregation.group("source","language").count().as("total");
Aggregation aggregation = Aggregation.newAggregation( operation);
AggregationResults<Map> result = mongoTemplate.aggregate(aggregation,"base_info", Map.class);
// 获取结果
result.getMappedResults()
先按照时间分组 ,再按照source分组统计
[
{
$match: {
create_time: {
$gte: { $date: "2024-03-01T06:25:59" },
$lte: { $date: "2024-04-23T06:25:59" },
},
},
},
{
$project: {
date: {
$dateToString: {
format: "%Y-%m-%d",
date: "$create_time",
},
},
source: 1,
},
},
{
$group: {
_id: { date: "$date", source: "$source" },
sourceTotal: { $sum: 1 },
},
},
{ $sort: { "_id.date": 1 } },
{
$project: {
sourceTotal: 1,
date: "$_id.date",
source: "$_id.source",
},
},
]
// 根据时间 create_time筛选数据
Criteria criteria = Criteria.where("create_time")
.gte(new Date(1709298601000L))
.lte(new Date(1711977001000L));
MatchOperation matchOperation = Aggregation.match(criteria);
// 格式化日期
ProjectionOperation projectionOperation = Aggregation.project()
.and(DateOperators.dateOf("create_time").toString("%Y-%m-%d"))
.as("date").andInclude("source");
// 按日期统计分组
GroupOperation groupOperation = Aggregation.group("date","source")
.count().as("source_count");
// 排序
SortOperation sortOperation = Aggregation.sort(Sort.Direction.ASC,"_id.date");
// 整理输出的字段格式
ProjectionOperation projectionOperation1 = Aggregation.project()
.andInclude("source_count")
.and("_id.date").as("date")
.and("_id.source").as("source");
// 定义聚合管道
Aggregation aggregation = Aggregation.newAggregation(
matchOperation,
projectionOperation,
groupOperation,
sortOperation,
projectionOperation1
).withOptions(AggregationOptions.builder().allowDiskUse(true).build());
AggregationResults<Map> result = mongoTemplate.aggregate(aggregation,
"base_info", Map.class);