The first aggregation pipeline stage uses the $lookup pipeline operator to join the users and loans collections. As with other complex examples discussed in this book, we first model the query using the mongo shell. Here is how the query might appear:
db.users.aggregate([
{ $match : { "userType" : "lender" }},
{ $project : { "userKey" : 1, "businessName" : 1, "address" : 1 }},
{ $lookup : { "from" : "loans", "localField" : "userKey",
"foreignField" : "lenderKey", "as" : "loans" }},
{ $addFields : { "total" : { "$sum" : "$loans.loanInfo.principal" }}},
{ $sort : { "address.country" : 1, "total" : -1 }}
]);
Now let's break this down into stages:
Stage | Notes |
$match | Adds documents to the pipeline from the users collection... |