Mongodb aggregation: $reduce not working as expected

Viewed 404

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 Answers
  • $max to get max value from key array of field a, 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 from key array of field a
  • check condition if maxValue and a 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

Related