Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing data url in Mongo DB

I am considering storing data-urls in my mongoDB instead of storing a reference to a file or using GridFS.

Data url:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMcAAAEsCAYAAAB38aczAAAgAElEQV

All of the files I am storing are JPG or PNG, and are less than 1MB in size.

I am wondering if this is considered bad practice, and what the performance implications for both read and write operations, storing the data-urls 1) in a separate collection 2) as meta data in a collection.

I'm open to any other suggestions for small file storage.

like image 567
TaylorMac Avatar asked Feb 14 '14 10:02

TaylorMac


People also ask

How do we store data in MongoDB?

Documents are used to store data in MongoDB. These documents are saved in JSON (JavaScript Object Notation) format in MongoDB. JSON documents support embedded fields, allowing related data and data lists to be stored within the document rather than in an external table. JSON is written in the form of name/value pairs.

Can we store media in MongoDB?

Large objects, or "files", are easily stored in MongoDB. It is no problem to store 100MB videos in the database. This has a number of advantages over files stored in a file system. Unlike a file system, the database will have no problem dealing with millions of objects.

What type of data can be stored in MongoDB?

Object ID − This datatype is used to store the document's ID. Binary data − This datatype is used to store binary data. Code − This datatype is used to store JavaScript code into the document. Regular expression − This datatype is used to store regular expression.


1 Answers

First, I wouldn't store base64 encoded data in a database that is perfectly capable of storing binary data. That's just waste of space. Store the image itself, not its base64 representation, i.e. not data : "VBORw0KGgoAAAANSUhEUgAAA...", but data : BinData("VBORw0KGgoAAAANSUhEUgAAA...") (the former is a string for MongoDB, the latter is binary data). Base64 increases the size by 33%.

Other than that, I think this is fine. The trade off is 1 request that grabs all the data vs. multiple requests. The downside of storing larger chunks of data is that all the data must be in RAM for a moment, but at 1MB that's probably a non-issue.

You should, however, make sure that you don't fetch the document in situations where you don't need the image. 1MB isn't too much, but for a read-heavy collection it's a disaster.

like image 113
mnemosyn Avatar answered Sep 22 '22 07:09

mnemosyn