【问题标题】:in Spring data mongo DB, how do we get city and its level count在 Spring data mongoDB 中,我们如何获取城市及其级别数
【发布时间】:2021-09-22 15:22:13
【问题描述】:

我的 json 结构存储在 Mongo DB 中。

[
   {
      "city":"Lodz",
      "level":1
   },
   {
      "city":"Warsaw",
      "level":1
   },
   {
      "city":"ssfd",
      "level":2
   },
   {
      "city":"rom",
      "level":5
   },
   {
      "city":"Lodz",
      "level":5
   },
   {
      "city":"Warsaw",
      "level":5
   },
   {
      "city":"Lodz",
      "level":1
   }
]

在春季数据中,我们如何按城市获取级别数。例如,城市“罗兹”有 2 个项目,华沙有 2 个项目。这是从 Mongo DB 获取这些数据的最佳方式

【问题讨论】:

  • 这个答案对你有帮助吗?

标签: mongodb spring-boot spring-mvc spring-data-jpa spring-data


【解决方案1】:

你可以做多种方式..让我们说

@Data
@AllArgsConstructor
@NoArgsConstructor
class Country {
  String city;
  int level;
}

您可以编写findAll() 查询并获取所有文档 List<Country> countries=countryRepository.findAll()

然后你就可以串流了

Map<String, Long> collect =
        countryList.stream()
            .collect(Collectors.groupingBy(Country::getCity, Collectors.counting()));
    System.out.println(collect);

现在你有了想要的输出。

如果您需要聚合的帮助,您可以编写一个简单的聚合来获得所需的输出

自动装配 Mongo 模板

@Autowired
private MongoTemplate mongoTemplate;

然后

Aggregation aggregation =
    Aggregation.newAggregation(Aggregation.group("city").count().as("count"))
        .withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());

List<Converter> countries =
    mongoTemplate
        .aggregate(aggregation, mongoTemplate.getCollectionName(Country.class), Converter.class)
        .getMappedResults();

您的 Converter 类可能是

@Data
@AllArgsConstructor
@NoArgsConstructor
class Converter {
  String _id;
  Long count;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-24
    • 1970-01-01
    • 1970-01-01
    • 2015-05-11
    • 2014-07-11
    • 2017-07-17
    • 1970-01-01
    相关资源
    最近更新 更多