[英]How do you optimally structure a MongoDB database to fetch all properties of a user?
I'm building an app where a user object has multiple game objects. 我正在构建一个用户对象具有多个游戏对象的应用程序。 What would be the proper strategy for fetching all of a user's games from a mongoDB database? 从mongoDB数据库中获取用户所有游戏的正确策略是什么?
As far as I can tell I have 2 options: 据我所知,我有两种选择:
eg example user 例如示例用户
{
_id: '1342',
name: 'Dave',
games: [
'12345678',
'fgnhe45rnd',
],
}
example game 示例游戏
{
_id: '12345678',
name: 'Fluxx',
}
eg example user 例如示例用户
{
_id: '1342',
name: 'Dave',
}
example game 示例游戏
{
_id: '12345678',
name: 'Fluxx',
users: [
'1342',
'5783',
],
}
Any advice is appreciated. 任何建议表示赞赏。 Thank you. 谢谢。
如果您需要用户游戏,则应使用1。例如,我需要kevin的游戏:您可以使用2获得kevin的游戏。
I will suggest you use the first option . 我建议您使用第一个选项 。
Example user 示例用户
{
_id: '1342',
name: 'Dave',
games: [
'12345678',
'fgnhe45rnd',
],
}
Example game 游戏范例
{
_id: '12345678',
name: 'Fluxx',
}
As you mentioned in the use case, you are fetching all of a user's games. 正如在用例中提到的那样,您正在获取用户的所有游戏。
So if you are fetching all of Dave's game, you only need to get Dave's list of games then refer each game to its data. 因此,如果您要获取Dave的所有游戏,则只需获取Dave的游戏列表,然后将每个游戏引用其数据即可。 This is 1+n fetch where n is number of game Dave has . 这是1 + n取 数,其中n是Dave拥有的游戏数量 。
If you use the second option, you will need to go through every single game to check if users list in the game contains Dave. 如果使用第二个选项,则需要检查每个游戏,以检查游戏中的用户列表是否包含Dave。 And then you have to record the data only if Dave is in the list. 然后,仅当Dave在列表中时,您才需要记录数据。 This is N fetch where N is total number of games in the database . 这是N次提取 ,其中N是数据库中的游戏总数 。
In general, N is larger than n+1. 通常,N大于n + 1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.