Mongodb聚合:$ reduce不能按预期工作 [英] Mongodb aggregation: $reduce not working as expected
问题描述
我有一个mongodb聚合 $ reduce
pipleine无法正常工作.这是我要实现的目标.
I have a mongodb aggregation $reduce
pipleine that is not working as expected. This is what I am trying to achieve.
基本上,我试图在给定属性中获取具有最高值的对象.在某些对象中, $ reduce
返回错误的对象,而在其他对象中,返回 null
,这意味着没有对象满足条件.
Basically I am trying to get the object with the highest value in a given property. In some objects $reduce
returns the wrong object in others it returns null
, meaning no object satisfied the condition.
我的代码具有group阶段和其他阶段,这些阶段会生成在 $ reduce
阶段中使用的变量.聚合管道中是否有任何已知的先前阶段可能会影响 $ reduce
阶段?
My code has the group stage and other stage that produce the variable used in the $reduce
stage. Are there any known preceding stages in the aggregation pipeline that might be affecting the $reduce
stage?
推荐答案
-
$ max
从字段a
的key
数组中获取最大值,这将返回-15
作为根据您的文件 -
$ filter
获取等于-15
值的对象 -
$ first
从$ filter
返回的结果中获取第一个对象
$max
to get max value fromkey
array of fielda
, this will return-15
as per your documents$filter
to get object that equal to-15
value$first
get first object from returned result from$filter
db.collection.aggregate([
{
$addFields: {
winner: {
$first: {
$filter: {
input: "$key",
cond: { $eq: ["$$this.a", { $max: "$key.a" }] }
}
}
}
}
}
])
使用 $ reduce
运算符的第二个选项
Second option using $reduce
operator,
- 在字段
a
的 - 检查条件,如果
maxValue
和a
值匹配,则返回最大对象
key
数组中的reduce,最大值中设置初始字段 maxValue
- set initial field
maxValue
in reduce, maximum value fromkey
array of fielda
- check condition if
maxValue
anda
value match then return max object
db.collection.aggregate([
{
$addFields: {
winner: {
$reduce: {
input: "$key",
initialValue: { maxValue: { $max: "$key.a" } },
in: {
$cond: [
{ $eq: ["$$this.a", "$$value.maxValue"] },
"$$this",
"$$value"
]
}
}
}
}
}
])
这篇关于Mongodb聚合:$ reduce不能按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!