I am writing an aggregation query where i want to perform a join in MongoDB between two collections and for that i am using $lookup, now my question is does $lookup change order of results by sort or not ?? because if it does that then i need to put my sort after $lookup and if not then i can use it before $lookup ??
My code is given 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
In MongoDB 3.6, the $lookup has a more expressive way where you can access the fields of the source document and do further pipeline operations within the $lookup stage. See documentation
As an example,
db.movies.aggregate([
{ $match : { _id : ObjectId("573a1390f29313caabcd414c")} },
{ $lookup : {from: "comments",
let: {'id' : '$_id' },
pipeline: [
{ $match : { '$expr': { '$eq': [ '$movie_id', '$$id' ] } }},
{ $sort: {'date': -1} }
],
as: "comments"
}
}
])
You have to declare any fields you want from the source collection in the let , do the matching as required (This is optional). Then you can use the pipeline stages that you need to apply in the collection being looked up.