Mongodb 聚合:$reduce 未按预期工作

Mongodb aggregation: $reduce not working as expected

我有一个 mongodb 聚合 $reduce pipleine 没有按预期工作。 This 是我想要达到的目标。

基本上我试图获得给定 属性 中具有最高值的对象。 In some objects $reduce returns wrong object in others it returns null, 意味着没有对象满足条件。

我的代码有小组阶段和其他阶段,这些阶段会产生 $reduce 阶段中使用的变量。聚合管道中是否有任何已知的可能影响 $reduce 阶段的先前阶段?

  • $maxkey 字段数组 a 中获取最大值,这将 return -15 根据您的文件
  • $filter 获取等于 -15
  • 的对象
  • $first$filter
  • 的 returned 结果中获取第一个对象
db.collection.aggregate([
  {
    $addFields: {
      winner: {
        $first: {
          $filter: {
            input: "$key",
            cond: { $eq: ["$$this.a", { $max: "$key.a" }] }
          }
        }
      }
    }
  }
])

Playground


第二个选项使用 $reduce 运算符,

  • 在 reduce 中设置初始字段 maxValue,字段 key 数组中的最大值 a
  • 检查条件,如果 maxValuea 值匹配,则 return 最大对象
db.collection.aggregate([
  {
    $addFields: {
      winner: {
        $reduce: {
          input: "$key",
          initialValue: { maxValue: { $max: "$key.a" } },
          in: {
            $cond: [
              { $eq: ["$$this.a", "$$value.maxValue"] },
              "$$this",
              "$$value"
            ]
          }
        }
      }
    }
  }
])

Playground