This question has already been asked before, please see this answer: https://stackoverflow.com/a/3011885/212159
The answer is now five years old. This was before the aggregation framework in Mongo existed. Is it now possible to achieve this using the aggregation framework without using nasty workarounds?