Storing Friend Relationships in MongoDB?

2019-01-21 15:07发布

问题:

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!

回答1:

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.



标签: mongodb