Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

211
Visualizações
Mongodb aggregation - min but not zero

I have a collection with array field:

{[
  name:String
  buyPrice:Int
  sellPrice:Int
]}

I am trying to find min and max buy/sell price. At some entries buy or sell price is zero so I need to find min price but greater than zero. Here is my query:

{
  name: '$_id',
  maxBuyPrice: {
    $max: '$commodities.buyPrice'
  },
  minBuyPrice: {
    $min: '$commodities.buyPrice'
  },
  maxSellPrice: {
    $max: '$commodities.sellPrice'
  },
  minSellPrice: {
    $min: '$commodities.sellPrice'
  }
}

I can't use $match operator with $gt because I can lost entries with max values

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

  • $filter to iterate loop of commodities.buyPrice array and get filtered price that is greater than 0
  • apply $min in above filtered result
  • $ifNull to check if above $min result is null then return only 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

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda