问题描述
我有mongo收藏:
{
"_id" : 123,"index" : "111","students" : [
{
"firstname" : "Mark","lastname" : "Smith"),}
],}
{
"_id" : 456,"index" : "222",}
{
"_id" : 789,"index" : "333","students" : [
{
"firstname" : "Neil",},{
"firstname" : "Sofia",}
我想获取具有给定索引集中的索引的文档,例如,givenSet = [“ 111”,“ 333”],并且具有最小学生数组长度。 结果应该是第一个具有_id:123的文档,因为它的索引在给定的set中,并且studentsArrayLength = 1,小于第三个。
我需要为Spring Mongo存储库编写自定义JSON @Query。我是Mongo的新手,对此问题有些困惑。
我写了这样的东西:
@Query("{'index':{$in : ?0},length:{$size:$students},$sort:{length:-1},$limit:1}")
Department getByMinStudentsSize(Set<String> indexes);
我应该只使用.count()还是类似的东西?
解决方法
对于这种类型的查询,您应该使用聚合框架。
-
根据您的条件过滤结果。
-
添加一个新字段并为其分配数组大小。
-
根据新字段进行排序。
-
限制结果。
解决方案应如下所示:
db.collection.aggregate([
{
"$match": {
index: {
"$in": [
"111","333"
]
}
}
},{
"$addFields": {
"students_size": {
"$size": "$students"
}
}
},{
"$sort": {
students_size: 1
}
},{
"$limit": 1
}
])
工作示例:https://mongoplayground.net/p/ih4KqGg25i6
,您遇到了问题,因为第二个参数应该用大括号括起来。第二个参数是投影
@Query("{{'index':{$in : ?0}},{length:{$size:'$students'}},$sort:{length:1},$limit:1}")
Department getByMinStudentsSize(Set<String> indexes);
下面是mongodb查询:
db.collection.aggregate(
[
{
"$match" : {
"index" : {
"$in" : [
"111","333"
]
}
}
},{
"$project" : {
"studentsSize" : {
"$size" : "$students"
},"students" : 1.0
}
},{
"$sort" : {
"studentsSize" : 1.0
}
},{
"$limit" : 1.0
}
],{
"allowDiskUse" : false
}
);