Database

[{"collection":"blogPosts","count":100,"content":{"_id":{"type":"autoincrement","autoType":"int"},"category":{"type":"faker","method":"BeerStyle","maxDistinctValue":10},"timestamp":{"type":"date","startDate":"2022-08-01T00:00:00Z","endDate":"2022-11-01T23:59:59Z"}}}]

Query

db.blogPosts.aggregate([{/** get max 3 items from category* sorted by timestamp*/"$group":{"_id":"$category","postsTop3":{"$topN":{"n":3,"sortBy":{"timestamp":1},"output":"$$ROOT"}}}},{/** aggregate all top3's*/"$group":{"_id":null,"posts":{"$push":"$postsTop3"}}},{/** sort them all by timestamp*/"$set":{"posts":{"$sortArray":{"input":{"$reduce":{"input":"$posts","initialValue":[],"in":{"$concatArrays":["$$value","$$this"]}}},"sortBy":{"timestamp":1}}}}},{"$unwind":"$posts"},{"$replaceWith":"$posts"}])

Result