Mongodb聚合:$ reduce不能按预期工作 [英] Mongodb aggregation: $reduce not working as expected

查看:76
本文介绍了Mongodb聚合:$ reduce不能按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个mongodb聚合 $ reduce pipleine无法正常工作.是我要实现的目标.

I have a mongodb aggregation $reduce pipleine that is not working as expected. This is what I am trying to achieve.

基本上,我试图在给定属性中获取具有最高值的对象.在某些对象中, $ reduce 返回错误的对象,而在其他对象中,返回 null ,这意味着没有对象满足条件.

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.

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

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?

推荐答案

  • $ max 从字段 a key 数组中获取最大值,这将返回 -15 作为根据您的文件
  • $ filter 获取等于 -15 值的对象
  • $ first $ filter
  • 返回的结果中获取第一个对象

    • $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" }] }
                }
              }
            }
          }
        }
      ])
      

      游乐场

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

      Second option using $reduce operator,

      • 在字段 a
      • key 数组中的reduce,最大值中设置初始字段 maxValue
      • 检查条件,如果 maxValue a 值匹配,则返回最大对象
      • 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"
                  ]
                }
              }
            }
          }
        }
      ])
      

      游乐场

      这篇关于Mongodb聚合:$ reduce不能按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆