In mongodb aggregation, where to apply sorting before search or after search?

I am writing an aggregation request where I want to make a connection in MongoDB between two collections, and for this I use $ lookup, now my question is whether $ lookup changes the order of the results by sorting or not? because if so, then I need to put my sort after $ lookup, and if not, can I use it before $ lookup ??

My code is below

brandmodel.aggregate(
     {$project: { '_id':0, 'brand_id': 1, 'brand_name':1, 'brand_icon':1, 'banner_image': 1, 'weight': 1} },
     {$lookup: {from: "student_coupons",localField: "brand_id",foreignField: "brand_id",as: "coupons"}},
     {$unwind : "$coupons"},
     {$sort: {weight: -1, "coupons.time_posted": -1}}, // SHOULD I WRITE THIS BEFORE LOOKUP OR AFTER LOOKUP
+4
source share

Source: https://habr.com/ru/post/1665976/


All Articles