Database

[{"collection":"questionBank","count":1000,"content":{"subject":{"type":"enum","values":["s1","s2","s3","s4","s5","s6","s7","s8","s9","s10"]},"difficulty":{"type":"enum","values":["easy","medium","hard"]}}},{"collection":"visitedQuestions","count":10,"content":{"userId":{"type":"objectId"}}}]

Query

db.questionBank.aggregate([{"$lookup":{"from":"visitedQuestions","localField":"_id","foreignField":"_id","pipeline":[{"$match":{/** the user's id that you are targeting*/"userId":ObjectId("5a934e000102030405000000")}}],"as":"visitedQuestionsLookup"}},{"$match":{/** not found in visitedQuestions*/"visitedQuestionsLookup":[]}},{"$set":{"visitedQuestionsLookup":"$$REMOVE","randomKey":{"$rand":{}}}},{"$setWindowFields":{"partitionBy":"$subject","sortBy":{"randomKey":1},"output":{"subjectRank":{"$rank":{}}}}},{"$setWindowFields":{"partitionBy":"$difficulty","sortBy":{"randomKey":1},"output":{"difficultyRank":{"$rank":{}}}}},{"$set":{"qualified":{"$and":[{"$switch":{"branches":[/** s1 - s5 <= 2*/{"case":{"$in":["$subject",["s1","s2","s3","s4","s5"]]},"then":{"$lte":["$subjectRank",2]}},/** s6 - s10 <= 3*/{"case":{"$in":["$subject",["s6","s7","s8","s9","s10"]]},"then":{"$lte":["$subjectRank",3]}}],"default":false}},{"$switch":{"branches":[/** 40% easy = 6*/{"case":{"$eq":["easy","$difficulty"]},"then":{"$lte":["$difficultyRank",6]}},/** 75% medium = 11.25*/{"case":{"$eq":["medium","$difficulty"]},"then":{"$lte":["$difficultyRank",11.25]}},/** 40% hard = 6*/{"case":{"$eq":["hard","$difficulty"]},"then":{"$lte":["$difficultyRank",6]}}],"default":false}}]}}},{"$match":{"qualified":true}},{"$sample":{"size":15}},{"$unset":["difficultyRank","qualified","randomKey","subjectRank"]}])

Result