我在mongoDB集合中有以下示例数据
{
"version": "1.1",
"platformName": "A",
"uri": "https://example.com/1e2b59da-44c1-44a4-aa03-b4487bde0c71"
}
{
"version": "1.1",
"platformName": "B",
"uri": "https://example.com/1e2b59da-44c1-44a4-aa03-b4487bde0c72"
}
{
"version": "1.1",
"platformName": "A",
"uri": "https://example.com/1e2b59da-44c1-44a4-aa03-b4487bde0c73"
}
我是通过基本查询和聚合,按值获取platformName的计数,例如A平台有2个计数,而B平台只有1个计数。
public List<CountDto> groupByFieldName(String fieldName, BasicQuery basicQuery) {
basicQuery.fields().include("id");
List<LcaProduct> lcaProductList = mongoTemplate.find(basicQuery, LcaProduct.class, "sample_collection");
List<String> productNames = lcaProductList.parallelStream().map(lcaProduct -> lcaProduct.getPlatformName()).collect(Collectors.toList());
Aggregation aggregation = newAggregation(
match(Criteria.where("platformName").in(productNames)),
group(fieldName)
.first(fieldName).as("name")
.count().as("count")
);
AggregationResults<CountDto> results = mongoTemplate.aggregate(aggregation, "sample_collection", CountDto.class);
return results.getMappedResults();
}
我必须使用两个查询,第一个使用basicQuery获取所有产品,第二个查询使用聚合来匹配第一个查询的结果。
我想使用单个查询获得所需的结果。是否可以与基本查询沿着执行聚合?
1条答案
按热度按时间fv2wmkja1#
您可以将初始查询前置到聚合中。