Database
db={users:[{_id:"abc",name:"boy",avatar:"..."},{_id:"xyz",name:"george",avatar:"..."},],chatusers:[{_id:1,userId:"abc",chatId:"123"},],chat:[{_id:"123",type:"dual"},],messages:[{_id:"z",chatId:"123",fromUserId:"xyz",type:"text",message:"hi"},]}
Query
db.chat.aggregate([{$match:{_id:{$in:["123"]}}},{$lookup:{from:"chatusers",let:{cId:"$_id"},pipeline:[{$match:{$expr:{$and:[{$eq:["$chatId","$$cId"]},{$ne:["$userId","xxx"]},],},},},],as:"ChatUser",},},{$unwind:"$ChatUser"},{$unwind:"$ChatUser.userId"},{$lookup:{from:"users",localField:"ChatUser.userId",foreignField:"_id",as:"Users",},},{$unwind:"$Users"},{$project:{"Users.password":0}},{$lookup:{from:"messages",let:{id:"$_id"},pipeline:[{$match:{$expr:{$eq:["$$id","$chatId"]}}},{$lookup:{from:"users",localField:"fromUserId",foreignField:"_id",as:"User"}},{$unwind:"$User"},{$project:{"User.password":0}},],as:"Messages",},},{$sort:{"Messages.createdAt":-1}},])