In previous tutorials, We have learned about MongoDB basics and installing MongoDB in Windows, as well as we learned about Inserting documents in MongoDB and selecting documents from MongoDB. In this tutorial, I am giving few examples of code which will help you when you have to work with images or other binary data types to store/retrieve/delete such data from MongoDB.
For CRUD operations, we will be using MongoDB’s GridFS APIs. In ideal situation, GridFS is a specification for storing and retrieving files that exceed the BSON-document size limit of 16MB. Instead of storing a file in a single document, GridFS divides a file into parts, or chunks, and stores each of those chunks as a separate document. By default GridFS limits chunk size to 255k. GridFS uses two collections to store files. One collection stores the file chunks, and the other stores file metadata.
When you query a GridFS store for a file, the driver or client will reassemble the chunks as needed. You can perform range queries on files stored through GridFS. You also can access information from arbitrary sections of files, which allows you to “skip” into the middle of a video or audio file.
GridFS is useful not only for storing files that exceed 16MB but also for storing any files for which you want access without having to load the entire file into memory.
Code Examples List Save an image into MongoDB Get/Retrieve an image from MongoDB Get/Retrieve all images from MongoDB Save the retrieved image into local file-system Delete an image from MongoDB
For testing purpose, I have stored an image in temp location (c: drive) named DemoImage.png. I will store this image into MongoDB.
Save an image into MongoDB
private static void saveImageIntoMongoDB(DB db) throws IOException { String dbFileName = "DemoImage"; File imageFile = new File("c:\\DemoImage.png"); GridFS gfsPhoto = new GridFS(db, "photo"); GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile); gfsFile.setFilename(dbFileName); gfsFile.save(); }
Get/Retrieve an image from MongoDB
private static void getSingleImageExample(DB db) { String newFileName = "c:/DemoImage"; GridFS gfsPhoto = new GridFS(db, "photo"); GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName); System.out.println(imageForOutput); } Output: { "_id" : { "$oid" : "53cff8d736414e8af4a4f0b8"} , "chunkSize" : 262144 , "length" : 138855 , "md5" : "b75f77c16c3ac6472365c06cde15d0da" , "filename" : "DemoImage" , "contentType" : null , "uploadDate" : { "$date" : "2014-07-23T18:03:03.403Z"} , "aliases" : null }
Get/Retrieve all images from MongoDB
private static void listAllImages(DB db) { GridFS gfsPhoto = new GridFS(db, "photo"); DBCursor cursor = gfsPhoto.getFileList(); while (cursor.hasNext()) { System.out.println(cursor.next()); } } Output: { "_id" : { "$oid" : "53cff8d736414e8af4a4f0b8"} , "chunkSize" : 262144 , "length" : 138855 , "md5" : "b75f77c16c3ac6472365c06cde15d0da" , "filename" : "DemoImage" , "contentType" : null , "uploadDate" : { "$date" : "2014-07-23T18:03:03.403Z"} , "aliases" : null }
Save the retrived image into local filesystem
private static void saveToFileSystem(DB db) throws IOException { String dbFileName = "DemoImage"; GridFS gfsPhoto = new GridFS(db, "photo"); GridFSDBFile imageForOutput = gfsPhoto.findOne(dbFileName); imageForOutput.writeTo("c:/DemoImageNew.png"); }
Delete an image from MongoDB
private static void deleteImageFromMongoDB(DB db) { String dbFileName = "DemoImage"; GridFS gfsPhoto = new GridFS(db, "photo"); gfsPhoto.remove(gfsPhoto.findOne(dbFileName)); }
Complete Example Code
Below is the complete for building above short examples. Feel free to play with it.
package examples.mongodb.crud; import java.io.File; import java.io.IOException; import com.mongodb.DB; import com.mongodb.DBCursor; import com.mongodb.MongoClient; import com.mongodb.gridfs.GridFS; import com.mongodb.gridfs.GridFSDBFile; import com.mongodb.gridfs.GridFSInputFile; public class MongoDBBinaryExample { public static void main(String[] args) throws IOException { MongoClient mongo = new MongoClient("localhost", 27017); DB db = mongo.getDB("howtodoinjava"); //Save a image in DB saveImageIntoMongoDB(db); //Get a image from DB getSingleImageExample(db); //Get all images from DB listAllImages(db); saveToFileSystem(db); //Delete images from DB deleteImageFromMongoDB(db); //Verifying if image was deleted or not getSingleImageExample(db); } private static void saveImageIntoMongoDB(DB db) throws IOException { String dbFileName = "DemoImage"; File imageFile = new File("c:\\DemoImage.png"); GridFS gfsPhoto = new GridFS(db, "photo"); GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile); gfsFile.setFilename(dbFileName); gfsFile.save(); } private static void getSingleImageExample(DB db) { String newFileName = "c:/DemoImage"; GridFS gfsPhoto = new GridFS(db, "photo"); GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName); System.out.println(imageForOutput); } private static void listAllImages(DB db) { GridFS gfsPhoto = new GridFS(db, "photo"); DBCursor cursor = gfsPhoto.getFileList(); while (cursor.hasNext()) { System.out.println(cursor.next()); } } private static void saveToFileSystem(DB db) throws IOException { String dbFileName = "DemoImage"; GridFS gfsPhoto = new GridFS(db, "photo"); GridFSDBFile imageForOutput = gfsPhoto.findOne(dbFileName); imageForOutput.writeTo("c:/DemoImageNew.png"); } private static void deleteImageFromMongoDB(DB db) { String dbFileName = "DemoImage"; GridFS gfsPhoto = new GridFS(db, "photo"); gfsPhoto.remove(gfsPhoto.findOne(dbFileName)); } } Output: { "_id" : { "$oid" : "53cff8d736414e8af4a4f0b8"} , "chunkSize" : 262144 , "length" : 138855 , "md5" : "b75f77c16c3ac6472365c06cde15d0da" , "filename" : "DemoImage" , "contentType" : null , "uploadDate" : { "$date" : "2014-07-23T18:03:03.403Z"} , "aliases" : null } { "_id" : { "$oid" : "53cff8d736414e8af4a4f0b8"} , "chunkSize" : 262144 , "length" : 138855 , "md5" : "b75f77c16c3ac6472365c06cde15d0da" , "filename" : "DemoImage" , "contentType" : null , "uploadDate" : { "$date" : "2014-07-23T18:03:03.403Z"} , "aliases" : null } null
That’s all for this simple tutorial. Hope it will help someone in need.
Happy Learning !!
Reference: http://docs.mongodb.org/manual/core/gridfs/