4

I have a e-commerce website working on MongoDB + GridFS. Each product may have up to 5 images. Each image has 3 thumbnails of different sizes.

I need an advice on best DB structure for this.

Currently I'm thinking to store image IDs and also thumb IDs (IDs from GridFS) in each product:

{
   '_id': 1, 
   'title': 'Some Product', 
   'images': [
               {'id': '11', thumbs: {'small': '22', 'medium': '33'},
               {'id': '44', thumbs: {'small': '55', 'medium': '66'}  
             ]
}

Or would it be better to store path in GridFS?

{
  '_id': '111',
  'filename': '1.jpg',
  'path': 'product/988/image/111/'
},
{
  '_id': '222',
  'filename': '1.jpg',
  'path': 'product/988/image/111/thumbnail_small'
},
{
  '_id': '333',
  'filename': '1.jpg',
  'path': 'product/988/image/111/thumbnail_large'
}

UPDATE: "path" field in GridFS is a "fake" path, not a real one. Just a quick way to find all related files. It is cheaper to have 1 indexed field than several fields with compound indexes.

Roman
  • 3,799
  • 4
  • 30
  • 41

1 Answers1

4

If you will store the images with GridFS within MongoDB, I would go with the first one.

The second schema doesn't seem to be correct. I mean GridFS is supposed to store files, so with the id of the image you don't need any path within those documents. If you simply want to store the path of the file, directly embedd it into your primary collection, so you don't need this overhead of a somewhat useless collection.

In general see Storing Images in DB - Yea or Nay? if you really should store your images in dbms.

Additionally if you only save the path you may need few to no changes in case you're switching to some CDN to get your images to the customer.

Community
  • 1
  • 1
philnate
  • 1,506
  • 2
  • 21
  • 39