Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

210
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!