Spring Mongo 聚合查询以从 MongoDB 中获取不同的国家名称和国家代码

Spring Mongo Aggregate query to fetch distinct country name and country code from MongoDB

我有一个名为 Location 的集合,它有几个属性,我只想获取不同的国家代码和国家名称。

下面的查询在 Mongo 数据库中工作正常。

db.location.aggregate([{"$group": {"_id": { countryCode: "$countryCode", countryName: "$countryName" }}}]);

我想将相同的查询转换为 SpringMongoReactiveAggretate 查询。下面的代码有一些问题。请帮我算出正确的代码。

@Repository
public class AggregateQueryRepository {
    
    @Autowired
    ReactiveMongoTemplate reactiveMongoTemplate;
    
    public Flux<Location> getAllCountryCodeAndCountry(String countryCode, String countryName) {
        Aggregation aggregation = newAggregation(
                match(Criteria.where("_id").is(countryCode).and(countryName)),
                group("_id").push("location").as("location")
        );
        Flux<Location> output
                = reactiveMongoTemplate.aggregate(aggregation, "location", Location.class);
        return output;
    }
}

您不需要 match 阶段,您应该将字段名称作为参数传递给 group

    public Flux<Location> getAllCountryCodeAndCountry() {
        Aggregation aggregation = newAggregation(
                group("countryCode", "countryName")
        );
        return reactiveMongoTemplate.aggregate(aggregation, "location", Location.class);
    }