计算MongoDB中最近7天嵌套嵌入文档的最小值

3pvhb19x  于 2022-11-03  发布在  Go
关注(0)|答案(1)|浏览(126)

我在MongoDB中有以下文档

{
    "product_id": "10001"
    "product_name": "Banana"
    "product_date": "2022-10-20T00:00:00.000+00:00"
    "product_price": 255.15
    "dates": {
        "2022-10-10": {
            "recorded_price": 195.15
        },
        "2022-10-15": {
            "recorded_price": 230.20
        },
        "2022-10-20": {
            "recorded_price": 255.20
        }
    }
}

我想添加一个名为"min_7day_price"的新字段,它将从日期对象中选择过去7天的最低价格。
大概是这样的:

{
    "product_id": "10001"
    "product_name": "Banana"
    "product_date": "2022-10-20T00:00:00.000+00:00"
    "product_price": 255.15
    "dates": {
        "2022-10-10": {
            "recorded_price": 195.15
        },
        "2022-10-15": {
            "recorded_price": 230.20
        },
        "2022-10-20": {
            "recorded_price": 255.20
        }
    },
    "min_7day_price": 230.20
}

我尝试使用aggregation创建一个新字段,并将对象转换为数组,但无法过滤其中的值。

{
  "min_7day_price": {
    $objectToArray: "$dates"
  }
}
hjzp0vay

hjzp0vay1#

一个选项是使用更新与管道:
1.将字典转换为数组
1.使用$reduce,通过迭代和比较当前项,只保留其中的一项:$$this到目前为止最好的项目:$$value
1.设置答案格式

db.collection.update({},
[
  {$set: {datesArr: {$objectToArray: "$dates"}}},
  {$set: {
      datesArr: {
        $reduce: {
          input: "$datesArr",
          initialValue: {
            k: {$dateAdd: {startDate: "$$NOW", amount: -7, unit: "day"}},
            v: {recorded_price: {$max: "$datesArr.v.recorded_price"}}
          },
          in: {
            $cond: [
              {$and: [
                  {$gte: [{$dateFromString: {dateString: "$$this.k"}}, "$$value.k"]},
                  {$lte: ["$$this.v.recorded_price", "$$value.v.recorded_price"]}
              ]},
              {
                k: {$dateFromString: {dateString: "$$this.k"}},
                v: "$$this.v.recorded_price"
              },
              "$$value"
            ]
          }
        }
      }
    }
  },
  {$set: {min_7day_price: "$datesArr.v", datesArr: "$$REMOVE"}}
])

了解它在playground example上的工作原理

相关问题