Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

214
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda