// MongoDB Playground // To disable this template go to Settings | MongoDB | Use Default Template For Playground. // Make sure you are connected to enable completions and to be able to run a playground. // Use Ctrl+Space inside a snippet or a string literal to trigger completions. // Select the database to use. use('test_FreePlanet'); let aggregation = [ { $match: { idapp: "13", $or: [ { deleted: { $exists: false, }, }, { deleted: { $exists: true, $eq: false, }, }, ], }, }, { $group: { _id: "$aportador_solidario", count: { $sum: 1, }, }, }, { $match: { "count": { $gte: 2 } } }, { $sort: { count: -1, }, }, { $lookup: { from: "users", let: { username: "$_id", idapp: "13", }, pipeline: [ { $match: { $expr: { $and: [ { $eq: [ "$$username", "$username", ], }, { $eq: [ "$$idapp", "$idapp", ], }, ], }, }, }, ], as: "user", }, }, { $unwind: "$user" }, { $replaceRoot: { newRoot: { $mergeObjects: [ "$user", "$$ROOT" ], }, }, }, { $project: { _id: 0, count: 1, aportador_solidario: 1, username: 1, name: 1, surname: 1, lasttimeonline: 1, idapp: 1, "profile.img": 1, }, }, ]; db.users.aggregate(aggregation);