GridFS

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.

When you query a GridFS store for a file, the Scala driver will reassemble the chunks as needed.

The following code snippets come from the GridFSTour.java example code that can be found with the driver source on github.

Prerequisites

Include the following import statements:

import java.nio.ByteBuffer
import java.nio.charset.StandardCharsets

import org.mongodb.scala._
import org.mongodb.scala.bson.BsonObjectId
import org.mongodb.scala.gridfs._
import org.mongodb.scala.model.Filters

import tour.Helpers._

import scala.util.Success
important

This guide uses the Observable implicits as covered in the Quick Start Primer.

Connect to a MongoDB Deployment

Connect to a MongoDB deployment and declare and define a MongoDatabase instance.

For example, include the following code to connect to a standalone MongoDB deployment running on localhost on port 27017:

val mongoClient: MongoClient = MongoClient()

For additional information on connecting to MongoDB, see Connect to MongoDB.

Create a GridFS Bucket

GridFS stores files in two collections: a chunks collection stores the file chunks, and a files collection stores file metadata. The two collections are in a common bucket and the collection names are prefixed with the bucket name.

The Scala driver provides the GridFSBucket() method to create the GridFSBucket.

val myDatabase = mongoClient.getDatabase("mydb")

// Create a gridFSBucket using the default bucket name "fs"
val gridFSBucket = GridFSBucket(myDatabase)

You can specify a bucket name to GridFSBuckets.create() method.

// Create a gridFSBucket with a custom bucket name "files"
val gridFSFilesBucket = GridFSBuckets(myDatabase, "files")
Note

GridFS will automatically create indexes on the files and chunks collections on first upload of data into the GridFS bucket.

Upload to GridFS

The GridFSBucket.uploadFromObservable methods read the contents of a Observable[ByteBuffer] and save it to the GridFSBucket.

You can use the GridFSUploadOptions to configure the chunk size or include additional metadata.

The following example uploads the contents of a Observable[ByteBuffer] into GridFSBucket:

// Get the input stream
val observableToUploadFrom: Observable[ByteBuffer] = Observable(
  Seq(ByteBuffer.wrap("MongoDB Tutorial..".getBytes(StandardCharsets.UTF_8)))
)

// Create some custom options
val options: GridFSUploadOptions = new GridFSUploadOptions()
    .chunkSizeBytes(358400)
    .metadata(Document("type" -> "presentation"))

val fileId: BsonObjectId = gridFSBucket.uploadFromObservable("mongodb-tutorial", observableToUploadFrom, options).headResult()

Find Files Stored in GridFS

To find the files stored in the GridFSBucket use the find method.

The following example prints out the filename of each file stored:

gridFSBucket.find().results().foreach(file => println(s" - ${file.getFilename}"))

You can also provide a custom filter to limit the results returned. The following example prints out the filenames of all files with a “image/png” value set as the contentType in the user defined metadata document:

gridFSBucket
  .find(Filters.equal("metadata.contentType", "image/png"))
  .results()
  .foreach(file => println(s" > ${file.getFilename}"))

Download from GridFS

The downloadToObservable methods return a Observable[ByteBuffer] that reads the contents from MongoDB.

To download a file by its file _id, pass the _id to the method. The following example downloads a file by its file _id:

val downloadById = gridFSBucket.downloadToObservable(fileId).results()

If you don’t know the _id of the file but know the filename, then you can pass the filename to the downloadToObservable method. By default, it will download the latest version of the file. Use the GridFSDownloadOptions to configure which version to download.

The following example downloads the original version of the file named “mongodb-tutorial”:

val downloadOptions: GridFSDownloadOptions = new GridFSDownloadOptions().revision(0)
val downloadByName = gridFSBucket.downloadToObservable("mongodb-tutorial", downloadOptions).results()

Rename files

If you should need to rename a file, then use the rename method.

The following example renames a file to “mongodbTutorial”:

val fileId: ObjectId = ??? //ObjectId of a file uploaded to GridFS

gridFSBucket.rename(fileId, "mongodbTutorial").printResults()
Note

The rename method requires an ObjectId rather than a filename to ensure the correct file is renamed.

To rename multiple revisions of the same filename, first retrieve the full list of files. Then for every file that should be renamed then execute rename with the corresponding _id.

Delete files

To delete a file from the GridFSBucket use the delete method.

The following example deletes a file from the GridFSBucket:

val fileId: ObjectId = ??? //ObjectId of a file uploaded to GridFS

gridFSBucket.delete(fileId).printResults()