Mongodb aggregation: $reduce not working as expected

拟墨画扇 提交于 2020-12-13 21:05:06

问题


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 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



来源:https://stackoverflow.com/questions/65039580/mongodb-aggregation-reduce-not-working-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!