首页 > 解决方案 > 春季启动查询以单独从子文档数组中的字段中获取最大值

问题描述

{
   "_id":"1",
   "name":"Elon musk",
   "created_by":"alien",
   "versions":[
      {
         "version":1,
         "active":true,
         "group":"ALL",
      },
      {
         "version":2,
         "active":false,
         "group":"ALL",
      }
   ]
  }

我需要一个返回最大值versions.version为 2的查询

val query = Aggregation.newAggregation(
            Aggregation.group("version").max("versions.version").as("maximum"),
            project("maximum").and("version").previousOperation())

val groupResults = mongoTemplate.aggregate(query, test::class.java, sample::class.java)

for (results in groupResults){
    println(results.maximum)
}

我在上面尝试过,但它只返回 1 但我期待 2 并且还有一个查询可以在@Query 需要帮助时使用!!!!

标签: mongodbspring-bootaggregate-functions

解决方案


这只是返回最大版本值,您可以自定义项目以获取其他字段

Arrays.asList(new Document("$match", 
    new Document("name", "Elon musk")), 
    new Document("$unwind", 
    new Document("path", "$versions")), 
    new Document("$sort", 
    new Document("versions.version", -1L)), 
    new Document("$limit", 1L), 
    new Document("$project", 
    new Document("version", "$versions.version")
            .append("_id", 0L)))

推荐阅读