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

150
Views
MongoDB - Find where list of nested documents has more than one field with a value greater than 0

I have a collection of User documents with the following shape:

// User

{
  payments: [
    { total: number }, 
  ],
}

The payments array of nested documents of variable length contains number totals with values equal to or greater than 0.

How do I find a list of Users where the length of payments with total > 0 is greater than one?

For example, I want to find documents like these:

// two totals > 0 ๐Ÿ‘
{
  payments: [
    { total: 50 }, 
    { total: 50 },
  ],
}
// two totals > 0 ๐Ÿ‘
{
  payments: [
    { total: 50 },
    { total: 0 },
    { total: 50 },
  ],
}
// three totals > 0 ๐Ÿ‘
{
  payments: [
    { total: 50 },
    { total: 50 }, 
    { total: 0 }, 
    { total: 50 }, 
  ],
}

but not these documents:

// not enough totals > 0 ๐Ÿ‘Ž
{
  payments: [
    { total: 50 }, 
    { total: 0 },
    { total: 0 }, 
  ],
}
// not enough totals > 0 ๐Ÿ‘Ž
{
  payments: [
    { total: 0 },
    { total: 0 }, 
  ],
}

Thank you for any help in advance!

over 4 years ago ยท Santiago Trujillo
1 answers
Answer question

0

Demo - https://mongoplayground.net/p/AG8Q1GqSEcl

You have to use an aggregation query.

$filter array where the total is greater than 0 and get the $size of filtered array. Check if it's greater than 1 $match

$project

db.collection.aggregate([
  {
    $project: {
      payments: "$payments",
      paymentsGreaterThanZero: {
        $size: {
          $filter: { input: "$payments", as: "item", cond: { $gt: [ "$$item.total",0 ] } }
        }
      }
    }
  },
  { $match: { paymentsGreaterThanZero: { $gt: 1 } } },
  { $project: { payments: "$payments" } }
])
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!