Database
[{"collection":"resources","count":20,"content":{"_id":{"type":"autoincrement","autoType":"int","startInt":0},"title":{"type":"faker","method":"CarType"},"type":{"type":"faker","method":"HackerNoun"},"url":{"type":"faker","method":"URL"},"createdDate":{"type":"date","startDate":"2022-01-01T00:00:00+00:00","endDate":"2022-05-10T23:59:59+00:00"}}},{"collection":"ratings","count":100,"content":{"_id":{"type":"autoincrement","autoType":"int","startInt":0},"resourceId":{"type":"int","minInt":0,"maxInt":20},"createdDate":{"type":"date","startDate":"2022-01-01T00:00:00+00:00","endDate":"2022-05-10T23:59:59+00:00"},"rating":{"type":"int","minInt":1,"maxInt":5},"review":{"type":"faker","method":"EmojiDescription"}}}]
Query
db.resources.aggregate([{/** filter resources*/"$match":{"title":{"$regex":"passenger","$options":"i"},"url":{"$regex":"https","$options":"i"}}},{/** get ratings for resource*/"$lookup":{"from":"ratings","localField":"_id","foreignField":"resourceId","pipeline":[{"$project":{"_id":0,"rating":1}}],"as":"ratings"}},{/** calculate average*/"$set":{"avgRating":{"$avg":"$ratings.rating"}}},{/** don't need ratings array anymore*/"$unset":"ratings"}])