Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing Friend Relationships in MongoDB?

Tags:

I was wondering what the best way of storing friend relationship data using MongoDB is?

Coming from mysql I had a separate table with friend relationships that had two foreign keys, each pointing to a friend in the "friendship" however, with MongoDB its possible to have arrays of references or even embedded documents..so whats the best way to store these relationships

Immediate first reaction was that I'd store an array of friend object ids in each user, however, that troubles me, because then, in order to remove a "friendship" I would have to do deletes on both friend's documents whereas if I stored the relationship in a separate collection (a la SQL) i could remove or add a relationship by just modifying one collection.

Thanks!

like image 576
Andy Tsen Avatar asked May 31 '11 04:05

Andy Tsen


People also ask

Can MongoDB handle relations?

In fact, MongoDB allows relationships between documents to be modeled via Embedded and Referenced approaches.

Can you create relationships in MongoDB?

To create a relationship in MongoDB, either embed a BSON document within another, or reference it from another. MongoDB databases work differently to relational databases. This is also true of relationships.

Does MongoDB allow ad hoc queries?

Ad-hoc queries are the queries not known while structuring the database. So, MongoDB provides ad-hoc query support which makes it so special in this case. Ad-hoc queries are updated in real time, leading to an improvement in performance.


1 Answers

Keeping a list of friend_ids in a user, is what I'll recommend. Few reasons,

1.You query a user, and you have list of all friends upfront available.

2.The requests (pending, accepted) can be handled as well, by seeing that a respective ids should be present in both the user's friends list. So, I can get list of actual and accepted friends by querying

my_id, my_friend_ids = user._id, user.friend_ids my_friends = db.users.find({'_id':{'$in': my_friend_ids}, 'friend_ids': my_id}) 

Yes, while removing a friendship, you have to $pull from friend-list of both the users, but frequency of that would be much less. But you query less in getting the friend-list, which would be used frequently.

like image 87
simplyharsh Avatar answered Sep 22 '22 06:09

simplyharsh