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

151
Visualizações
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 Respostas
Responde à pergunta

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 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