Instructions for Query1
- To start, perform a lookup to do the left join, ensuring that the joined card documents are stored as an array (the join occurs if the array contains the card
_id
)
- Next, sum up the clicks
- Then, sort by the field that has the sum
*For descending order, use sort -1
instead of 1
Test query here
mainColl.aggregate(
[{"$lookup":
{"from": "cardCollection",
"localField": "cards",
"foreignField": "_id",
"as": "clickSum"}},
{"$set": {"clickSum": {"$sum": "$clickSum.clicks"}}},
{"$sort": {"clickSum": 1}}])
Steps for Query2
- Similar to the previous query, but it performs the calculation before the join (slightly bigger code)
Test query here
mainColl.aggregate(
[{"$lookup":
{"from": "cardsCollection",
"localField": "cards",
"foreignField": "_id",
"pipeline":
[{"$group": {"_id": null, "clicksSum": {"$sum": "$clicks"}}}],
"as": "clicksSum"}},
{"$set": {"clicksSum": {"$arrayElemAt": ["$clicksSum.clicksSum", 0]}}},
{"$sort": {"clickSum": 1}}])