How to save binary files into MongoDB using java driver?

MongoDB GridFS is a specification for storing large files. (16 MB or more) All MongoDB drivers support GridFS. GridFS split the file into many chunks and store each chunk in each document.

GridFS stores documents in two collections.

  1. Chunk Collection.
  2. File Collection.

The first collection stores the binary chunk and the second collection store the meta data of the binary file.

Steps to save to Binary file like image or PDF into MongoDB.

  1. Create connection to MongoDB.
  2. Get the Database from Connection.
  3. Create GridFS object.
  4. Create GridFSInputFile and save.

Code snippet for saving binary file into MongoDB.

The above given code can be written in one line.

Both code snippets given above write the file into default bucket called ‘fs’.

We can write the binary file into a specific bucket also. For that we need to give the bucket name as the second argument to create GridFS object.

Write binary file into specific bucket.

Complete Sample Code

You can verify the binary file save operation using mongo or mongofiles command line tools.

List files using mongofiles utility

mongofiles utility connected to MongoDB instance installed in the localhost and listed all files in the reports DB.

Query files collection using mongo utility

MongoDB Java Driver API
MongoDB GridFS Documentation

One thought on “How to save binary files into MongoDB using java driver?

  1. ps said:

    How can you read the same binary file in chunks?