Code
mongodb
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $group: {
_id: "$customerId",
total: { $sum: "$amount" },
count: { $sum: 1 }
}},
{ $sort: { total: -1 } },
{ $limit: 10 },
{ $project: {
customer: "$_id",
total: 1,
avgOrder: { $divide: ["$total", "$count"] },
_id: 0
}},
{ $lookup: {
from: "customers",
localField: "customer",
foreignField: "_id",
as: "customerInfo"
}}
]);