6

I'm using MongoDB to store user profiles, and now I want to use GridFS to store a picture for each profile.

The two ways I'm comparing linking the two documents are:

A) Store a reference to the file ID in the user's image field:

User: 
{
  "_id": ObjectId('[user_id here]'),
  "username": 'myusername',
  "image": ObjectId('[file_id here]')
}

B) Store a reference to the user in the file's metadata:

File metadata: 
{
  "user_id": ObjectId('[user_id here]')
}

I know in a lot of ways it's up to me and dependent on the particulars of the app (it'll be mobile, if that helps), but I'm just wondering if there's any universal benefit to doing it one way or the other?

4

1 回答 1

5

这里的答案实际上取决于您的应用程序的使用模式。我的假设(请随时纠正我)是最可能的模式是这样的:

查找用户 --> 查找用户 --> 显示配置文件(获取图片)

在这个通用用例中,使用方法 A,您可以找到包含图像对象 ID 的用户文档,以显示配置文件,然后您随后使用该 ID 获取文件(2 个基本操作,您就完成了)。

注意:从 GridFS 实际获取文件我将其视为单个逻辑操作,实际上涉及多个操作,但大多数驱动程序/API 无论如何都掩盖了这一点。

使用方法 B,您将不得不找到用户文档,然后执行另一个查询以在文件元数据集合中找到相关的 user_id,然后去获取文件。据我计算,这是三个操作(方法 A 没有的额外发现)。

那有意义吗?

当然,如果我的假设不正确并且您的应用程序是(例如)图像驱动的,那么您的查询模式可能会得出不同的答案。

于 2012-01-25T15:36:10.007 回答