【问题标题】:Find where property of object in array is bigger than property in other object查找数组中对象的属性大于其他对象中的属性的位置
【发布时间】:2021-12-26 01:10:42
【问题描述】:

我尝试查找对象中的属性 rate 大于其他对象中的属性 rate 的文档(两者都在同一个数组中)

示例文档:

{
  "rates": [
    {
      "name": "x",
      "rate": 5
    },
    {
      "name": "y",
      "rate": 4
    }
  ]
}

我就是这样尝试的:

db.ratesCollection.find({  
  $where: 
    {"rates": { $elemMatch: {name: "x", "rate"}}} > 
    {"rates": { $elemMatch: {name: "y", "rate"}}} 
}).pretty()

问题是当我首先需要在数组中查找对象时,我不知道如何比较值。

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

    您可以使用$reduce 处理数组并首先获取x_ratey_rate。然后比较两个值得到结果。

    db.collection.aggregate([
      {
        "$addFields": {
          "x_rate": {
            "$reduce": {
              "input": "$rates",
              "initialValue": null,
              "in": {
                $cond: [
                  {
                    $eq: [
                      "$$this.name",
                      "x"
                    ]
                  },
                  "$$this.rate",
                  "$$value"
                ]
              }
            }
          },
          "y_rate": {
            "$reduce": {
              "input": "$rates",
              "initialValue": null,
              "in": {
                $cond: [
                  {
                    $eq: [
                      "$$this.name",
                      "y"
                    ]
                  },
                  "$$this.rate",
                  "$$value"
                ]
              }
            }
          }
        }
      },
      {
        $match: {
          $expr: {
            $gt: [
              "$x_rate",
              "$y_rate"
            ]
          }
        }
      },
      {
        "$project": {
          x_rate: false,
          y_rate: false
        }
      }
    ])
    

    这是Mongo playground 供您参考。

    【讨论】:

      【解决方案2】:

      查询

      • x>y x-y > 0
      • 减少找到x-y并检查它是否大于0
      • 初始 value=0 如果我们找到 x 我们添加如果我们找到 y 减去,否则保持原样

      Test code here

      aggregate(
      [{"$match":
        {"$expr":
         {"$gt":
          [{"$reduce":
            {"input":"$rates",
             "initialValue":0,
             "in":
             {"$switch":
              {"branches":
               [{"case":{"$eq":["$$this.name", "x"]},
                 "then":{"$add":["$$value", "$$this.rate"]}},
                {"case":{"$eq":["$$this.name", "y"]},
                 "then":{"$subtract":["$$value", "$$this.rate"]}}],
               "default":"$$value"}}}},
           0]}}}])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-09
        • 1970-01-01
        • 1970-01-01
        • 2022-07-08
        相关资源
        最近更新 更多