简体   繁体   English

您如何优化构造MongoDB数据库以获取用户的所有属性?

[英]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: 据我所知,我有两种选择:

  1. Give users a game property that is an array of ids of games that the user has and then fetch each game individually 给用户一个游戏属性,该属性是用户拥有的游戏ID的数组,然后分别获取每个游戏

eg example user 例如示例用户

{
  _id: '1342',
  name: 'Dave',
  games: [
    '12345678',
    'fgnhe45rnd',
  ],
}

example game 示例游戏

{
  _id: '12345678',
  name: 'Fluxx',
}
  1. The opposite. 相反。 Give each game a users property that is an array of ids of users that own that game. 给每个游戏一个用户属性,该属性是拥有该游戏的用户ID的数组。 Then fetch all games that have a specific user's id. 然后获取所有具有特定用户ID的游戏。

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的游戏。

Use Case 用例

  1. A user object has multiple game objects 一个用户对象具有多个游戏对象
  2. To fetching all of a user's games 提取用户的所有游戏

I will suggest you use the first option . 我建议您使用第一个选项

Example user 示例用户

{
  _id: '1342',
  name: 'Dave',
  games: [
    '12345678',
    'fgnhe45rnd',
  ],
}

Example game 游戏范例

{
  _id: '12345678',
  name: 'Fluxx',
}

Reason 原因

As you mentioned in the use case, you are fetching all of a user's games. 正如在用例中提到的那样,您正在获取用户的所有游戏。

First Option 第一选择

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拥有的游戏数量

Second Option 第二选择

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM