问题
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:
- $maxto get max value from- keyarray of field- a, this will return- -15as per your documents
- $filterto get object that equal to- -15value
- $firstget 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 maxValuein reduce, maximum value fromkeyarray of fielda
- check condition if maxValueandavalue 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