在MongoDB中存储朋友关系? [英] Storing Friend Relationships in MongoDB?
问题描述
我想知道使用MongoDB存储朋友关系数据的最佳方法是什么?
I was wondering what the best way of storing friend relationship data using MongoDB is?
来自mysql,我有一个单独的表,该表具有两个具有两个外键的朋友关系,每个外键都指向友谊"中的一个朋友,但是,使用MongoDB可能具有引用数组甚至嵌入式文档.存储这些关系的最佳方法
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
立即的第一反应是我要在每个用户中存储一个朋友对象ID的数组,但是这困扰着我,因为那样,为了删除友谊",我必须对两个朋友的文档进行删除,而如果将关系存储在单独的集合中(如SQL),则可以通过仅修改一个集合来删除或添加关系.
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.
谢谢!
推荐答案
在用户中保存friend_ids
列表.出于几个原因,
Keeping a list of friend_ids
in a user, is what I'll recommend. Few reasons,
1.您查询一个用户,并且可以预先获得所有朋友的列表.
1.You query a user, and you have list of all friends upfront available.
2.通过查看两个用户的好友列表中都应包含相应的ID,也可以处理请求(待处理,已接受).因此,我可以通过查询获取实际和接受的朋友的列表
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})
是的,在删除友谊时,您必须从两个用户的朋友列表中$pull
,但是这样的频率要少得多.但是您在获取朋友列表方面的查询较少,而该列表会经常使用.
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中存储朋友关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!