Simulating relations in MongoDB Simulating relations in MongoDB mongodb mongodb

Simulating relations in MongoDB


Both are valid solutions, the advantage of solution 1 is that you can show a page like this with retrieving only one document from the db. Users don't update their profile very often and you can update all posts and embedded comments async after a user profile is changed. You can index the posts and embedded comments on userid so the update should be fast. Updating in mongodb is very speedy because mongodb does an update-in-place and you can't rollback or commit so mongodb doesn't have to log the changes.

However users on sites like stackoverflow also have a reputation and this reputation changes a lot more than their profile.

Solution 2 requires the retrieving of more documents per page, however you can use the $in operator with a list of userid's (userid of post+userid's of comments) so you only need two "selects statements".


I faced a similar issue and this is how I solved it :

(When I solved this issue, my driving motivation was to avoid joins)

use 2 separate collection : one for USERS and one for POSTS. Store the user object along with the post in the posts collections. Do not update the posts collection when the user object is changed. maintain the user information is the USERS collection. Sure the post data would end up containing stale user information but how often does the user change his/her profile.

If you have to show the absolute latest user information along with each posts , then retrieve the user information from a cache.

Hope this works for you. My solution is still in development so I do not have load test results to share with you.