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.
$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 filteredconst 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);
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}
}
}
]);