mongodb - 春季启动查询以单独从子文档数组中的字段中获取最大值
问题描述
{
"_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
需要帮助时使用!!!!
解决方案
这只是返回最大版本值,您可以自定义项目以获取其他字段
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)))
推荐阅读
- c# - 无法在脚本生成的多个位置上实例化一副纸牌
- python-3.x - 为什么这个 RegEx 不匹配任何东西?
- laravel - 用户定义函数在 Route::get() 中有效,但在 Route::group() 中无效
- javascript - 我想创建背景音乐,但它不会自动播放?
- java - 拥有唯一键以更好地聚合 MongoDB 中的数据是个好主意吗
- c - 删除分配的字符串数组
- java - 使用 Gradle 在 Java 测试中使用 Scala 类
- python - 无效语法python的未知原因
- html - CSS 文件未应用于页面,未在源下加载
- python - Python检查列表中不定数量的连续元素是否满足条件