How should i design Users and Friends table when using MongoDB (Rails)

mongodb, mongoid, ruby-on-rails

Solution

One user has 30 000 000 friends.

Seriously? The biggest following on the Chinese edition of Twitter, Sina Weibo, where the number of followers per person dwarfs both Facebook and Twitter combined is like 20 million for a single person. That is however rare.

That being said, housing the friend relationship within the root document as the docs ( http://docs.mongodb.org/manual/core/data-modeling/ ) and @jorscas suggests would not be wise at all.

I can easily imagine the document growing at a consistently fast rate as a user spends more time on the site accessing more friend relaitonships. This would be bad for a couple of reasons, one for fragmentation of space within MongoDBs extents and two because fast growing documents will probably need moving on the disk, which in itself is a slow and intensive operation. There are more reasons but that's enough.

You have also got to consider the 16meg limit, even 8,000 connections would reach that limit.

So already I would say not to embed. You know the way you would design this in a relational model? I would do that, denormalising when needed while normalising the relationship between users.

Problem

I am working in a Social Network kind of project, and the suggested database is MongoDB. I have worked with various projects before and have designed databases in an Relation Database system, but as i am new to NoSQL db (MongoDB). I am stuck with designing stuff. Consider the below example, 1) The app will have Users and Friends table to hold data of Users and Friends of the users. Now, is the below design correct? users : ``` _id username password other_fields ---------------------------------------- 2gsyexej2 balan adsfasf .. ``` user_friends : ``` _id user_id friends -------------------- 1 2gsyexej2 friends - 0 - friend_user_id = asdfdf23adfsasdf - 1 - friend_user_id = efex89sdfsw0dfssf etc., ``` In above model, i have used "Manual Reference", took the user id from users table and used it as reference in user_friends table. is this approach correct? if not please suggest a better approach. thanks, Balan

Original source