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

197
Visualizações
Replica of "for" loop in mongoose aggregation

I have some code as this

const quizzes = await Quiz.find({});
        const filtered = [];
        for (const quiz of quizzes){
            const response = await Response.aggregate([
                {
                    $match: {
                        userID: `${userID}`, 
                        quizID: `${quiz._id}`
                    }
                }
            ]);
            if (response.length === 0){
                filtered.push(quiz._id);
            }
        }
       console.log(filtered);

I want to write a aggregate method to replace my for loop, how can I achieve this? I assume there is no requirement to post my schema's, all I need is help with how to traverse a whole collection items and perform some query on them with some other collection.

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

0

  • $lookup to join response collection and match quizID and userID not equal to input userID
  • $match if returned response from lookup is not empty
  • $group by null and construct array of quizID in filtered
const response = await Quiz.aggregate([
  {
    $lookup: {
      from: "response",
      let: { quizID: "$_id" },
      pipeline: [
        {
          $match: {
            userID: { $ne: userID },
            $expr: { $eq: ["$$quizID", "$quizID"] }
          }
        }
      ],
      as: "response"
    }
  },
  { $match: { response: { $ne: [] } } },
  {
    $group: {
      _id: null,
      filtered: { $push: "$_id" }
    }
  }
]);

const filtered = response.length ? response[0].filtered : [];
console.log(filtered);

Playground

over 4 years ago · Santiago Trujillo Relatório

0

I suppose, it would be great if you have provided models as well, but anyway if you want to remove for loop here what I suggest:

quizz_ids = quizzes.map(q => q._id);
const responses = await Response.aggregate([
            {
                $match: {
                    userID: `${userID}`, 
                    quizID: { $in: quizz_ids}
                }
            }
        ]);
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