use('test_FreePlanet'); let passo1 = [ { $sort: { transactionDate: -1, }, }, { $match: { idapp: "13", $or: [ { accountFromId: "632b300002f403d67895d79c", }, { accountToId: "632b300002f403d67895d79c", }, ], }, }, { $lookup: { from: "accounts", localField: "accountFromId", foreignField: "_id", as: "accfrom", }, }, { $unwind: "$accfrom", }, { $lookup: { from: "users", let: { username: "$accfrom.username", idapp: "$accfrom.idapp", }, pipeline: [ { $match: { $expr: { $and: [ { $eq: [ "$$username", "$username", ], }, { $eq: [ "$$idapp", "$idapp", ], }, ], }, }, }, ], as: "userfrom", }, }, { $unwind: "$userfrom", }, { $lookup: { from: "accounts", localField: "accountToId", foreignField: "_id", as: "accto", }, }, { $unwind: "$accto", }, { $lookup: { from: "circuits", localField: "accfrom.circuitId", foreignField: "_id", as: "circuitfrom", }, }, { $unwind: "$circuitfrom", }, { $lookup: { from: "circuits", localField: "accto.circuitId", foreignField: "_id", as: "circuitto", }, }, { $unwind: "$circuitto", }, { $lookup: { from: "users", let: { username: "$accto.username", idapp: "$accto.idapp", }, pipeline: [ { $match: { $expr: { $and: [ { $eq: [ "$$username", "$username", ], }, { $eq: [ "$$idapp", "$idapp", ], }, ], }, }, }, ], as: "userto", }, }, { $unwind: "$userto", }, { $project: { transactionDate: 1, amount: 1, causal: 1, notifId: 1, "circuitfrom.symbol": 1, "circuitto.symbol": 1, "userfrom.username": 1, "userfrom.profile.img": 1, "userto.username": 1, "userto.profile.img": 1, }, }, { $group: { _id: null, count: { $sum: 1, }, results: { $push: "$$ROOT", }, }, }, { $project: { count: 1, rows: { $slice: [ "$results", 0, 20, ], }, }, } ]; let passo2 = []; let passo2b = [ ]; let passo3 = [ ]; let aggregation = []; let test = false; if (test) { aggregation = [...aggregation, ...passo4]; } else { aggregation = [...aggregation, ...passo1]; aggregation = [...aggregation, ...passo2]; aggregation = [...aggregation, ...passo2b]; aggregation = [...aggregation, ...passo3]; } db.movements.aggregate(aggregation);