Mongo Playground

Configuration

db={"messages":[/** group message*/{id:1,text:"hello",chat_id:"AjK954_e5iP",created_at:13761512345},/** private message*/{id:2,text:":)",chat_id:"Bho9Sr_f51Rz",created_at:13762212345}],"members":[/** group chat member*/{user_id:"A",chat_id:"AjK954_e5iP",type:"group"},/** private chat member*/{user_id:"A",chat_id:"Bho9Sr_f51Rz",type:"private"}]}

Query

db.members.aggregate([{"$match":{user_id:"A"}},{"$lookup":{"from":"messages","localField":"chat_id","foreignField":"chat_id","as":"thechats"}},{"$unwind":"$thechats"},{"$replaceWith":"$thechats"},{"$sort":{created_at:-1}},{"$limit":20}])

Result