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

247
Visualizações
mongoose get only those documents if all subdocuments pass the criteria

Let's say I have a Lesson schema and it contains an array of question subdocuments. How would I get those lessons where it is marked as completed but all the questions in the array have isDeleted: true

I thought of something like

Lesson.find({ isComplete: true, 'questions.isDeleted': true })

but that gets the lessons if at least one of the questions is deleted. How would I assert the condition for all of the questions?

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

0

You can't use the dot notation as it flattens the array, What you can do is use $expr, this allows the use of aggregation operators, like $reduce.

Now we can iterate over the array and see if all the documents satisfy the conditions, like so:

db.collection.find({
  isComplete: true,
  $expr: {
    $eq: [
      {
        $reduce: {
          input: "$questions",
          initialValue: 0,
          in: {
            $sum: [
              "$$value",
              {
                $cond: [
                  {
                    $ne: [
                      "$$this.isDeleted",
                      true
                    ]
                  },
                  1,
                  0
                ]
              }
            ]
          }
        }
      },
      0
    ]
  }
})

Mongo 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