问题
I have a mongodb aggregation $reduce
pipleine that is not working as expected. This is what I am trying to achieve.
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.
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?
回答1:
$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" }] }
}
}
}
}
}
])
Playground
Second option using $reduce
operator,
- 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"
]
}
}
}
}
}
])
Playground
来源:https://stackoverflow.com/questions/65039580/mongodb-aggregation-reduce-not-working-as-expected