I tackled this exact problem a while ago.
There are no joins in mongo. You have to manually take care of the join.
Your options are:
- Loop through each comment entry and query mongo for the user. this is what you're doing.
- Get all user id's from comments, query mongo for the users matching these ids, then take care to match user to comment.This is just what you did but a little more optimized.
- Embed the user in comments or comments in users. Wouldn't recommend this, this is probably not the right place for comments/users.
- Think of what set of data do you need from user when displaying a comment, and embed just this info in comment
I ended up going with the last option.
We embedded the user id, first and last name in each comment.
This info is unlikely to change (possibly not even allowed to change after creation?).
If it can change then it is not too hard to tailor the update-user method to update the related comments with the new info (we did that too).
So now no join is needed.