Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mongodb聚合-最小但不是零_Mongodb_Aggregation Framework - Fatal编程技术网

Mongodb聚合-最小但不是零

Mongodb聚合-最小但不是零,mongodb,aggregation-framework,Mongodb,Aggregation Framework,我有一个带有数组字段的集合: {[ name:String buyPrice:Int sellPrice:Int ]} 我试图找到最小和最大买入/卖出价格。在某些条目中,买入或卖出价格为零,所以我需要找到最小价格,但大于零。 我的问题是: { name: '$_id', maxBuyPrice: { $max: '$commodities.buyPrice' }, minBuyPrice: { $min: '$commodities.buyPrice

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

{[
  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
    迭代
    商品的循环。buyPrice
    数组并获取大于0的筛选价格
  • 在上述过滤结果中应用
    $min
  • $ifNull
    要检查上述
    $min
    结果是否为null,请仅返回0

请注意,如果所有输入值均为空,则此选项将给出空值0@TomSlabbaert谢谢,我已经用解决方案更新了答案。非常感谢。投了赞成票,但我有
  {
    $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
        ]
      }
    }
  }