Search code examples
mongodbmongo-javamongo-java-driver

How can I store any image (size 1mb) in mongoDB?


How can I store any image (size 1mb) in mongoDB. I know if it's more than 16MB then I should use GRIDFS. But what is the best way if size is around 1-10 MB.


Solution

  • Read the content of the image file into a byte[]. The driver will then store it in MongoDB as the BSON binary type. When your application can handle multiple image formats, you should also store the filetype in a different field so you know how to decode it when reading it back into the application.