在mongoDb中分组并内部加入

时间:2018-10-08 06:40:03

标签: mongodb mongoose

从on集合中查找用于分组依据的第二个集合的详细信息的最佳方法。

db.projects.aggregate([{ 
$group: { 
    _id: "$client_id", 
    totalRevenue: { $sum: { $add: [ "$expenditure.client_billing"] } 
},
} }] );

现在我需要从用户集合中查找客户端详细信息。

1 个答案:

答案 0 :(得分:0)

db.projects.aggregate([{ 
$group: { 
    _id: "$client_id", 
    totalRevenue: { $sum: "$expenditure.client_billing" },
}},{
$lookup:{
    from: "users", localField: "_id", foreignField: "_id", as: "details"
}},{ $match: {
    details: {$ne: []}
    }},{
$project:{
    "totalRevenue":1,        
    client_name: { $concat: [ {"$arrayElemAt":["$details.first_name",0]},' ', {"$arrayElemAt":["$details.last_name",0]}] }
}}])

没有$ unwind