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

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

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 Report

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