gpt4 book ai didi

Mongodb 聚合 - 分钟但不为零

转载 作者:行者123 更新时间:2023-12-04 07:58:53 29 4
gpt4 key购买 nike

我有一个带有数组字段的集合:

{[
name:String
buyPrice:Int
sellPrice:Int
]}
我试图找到最低和最高买入/卖出价格。在某些条目中,买入或卖出价格为零,因此我需要找到最低价格但大于零。
这是我的查询:
{
name: '$_id',
maxBuyPrice: {
$max: '$commodities.buyPrice'
},
minBuyPrice: {
$min: '$commodities.buyPrice'
},
maxSellPrice: {
$max: '$commodities.sellPrice'
},
minSellPrice: {
$min: '$commodities.sellPrice'
}
}
我不能用 $match运营商 $gt因为我可能会丢失最大值的条目

最佳答案

  • $filter迭代 commodities.buyPrice 的循环数组并获取大于 0 的过滤价格
  • 申请 $min在上面的过滤结果中
  • $ifNull检查是否高于 $min结果为空然后只返回 0
  •   {
    $project: {
    name: "$_id",
    maxBuyPrice: { $max: "$commodities.buyPrice" },
    minBuyPrice: {
    $ifNull: [
    {
    $min: {
    $filter: {
    input: "$commodities.buyPrice",
    cond: { $gt: ["$$this", 0] }
    }
    }
    },
    0
    ]
    },
    maxSellPrice: { $max: "$commodities.sellPrice" },
    minSellPrice: {
    $ifNull: [
    {
    $min: {
    $filter: {
    input: "$commodities.sellPrice",
    cond: { $gt: ["$$this", 0] }
    }
    }
    },
    0
    ]
    }
    }
    }
    Playground

    关于Mongodb 聚合 - 分钟但不为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66568333/

    29 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com