Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to store references to a gridFS file in a document?

Tags:

mongodb

gridfs

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?

like image 852
Matt Stauffer Avatar asked Jan 24 '12 19:01

Matt Stauffer


1 Answers

The answer here really depends on your application's usage pattern. My assumption (feel free to correct me) is that the most likely pattern is something like this:

Look Up User --> Find User --> Display Profile(Fetch Picture)

With this generalized use case, with method A, you find the user document, to display the profile) wich contains the image object ID and you subsequently fetch the file using that ID (2 basic operations and you are done).

Note: the actual fetching of the file from GridFS I am treating as a single logical operation, in reality there are multiple operations involved, but most of the drivers/APIs obscure this anyway.

With method B, you are going to have to find the user document, then do another query to find the relevant user_id in the file metadata collection, then go fetch the file. By my count, that is three operations (an extra find you do not have with method A).

Does that make sense?

Of course, if my assumption is incorrect and your application is (for example) image driven, then your query pattern may come up with a different answer.

like image 104
Adam Comerford Avatar answered Oct 21 '22 06:10

Adam Comerford