How to overwrite image in mongoDB gridfs?

4.2k views Asked by At

I am using MongoDB 3.2 and Java 1.8 version and mongo-java driver. I have saved images in database. I am able to save image, read image and read all images. Now I want to update image in GridFS. I want to overwrite image if name of image is same. When I tried to save image with same name, I am getting two images. I am using following code to save image.

GridFSBucket gridFSBucket = GridFSBuckets.create(database, imageCollection);
        InputStream streamToUploadFrom = new FileInputStream(new File(imageFileName));
        GridFSUploadOptions options = new GridFSUploadOptions()
                .metadata(new Document("type", "brand").append("name", name).append("uuid", UUID.randomUUID().toString()));
        ObjectId fileId = gridFSBucket.uploadFromStream(name, streamToUploadFrom, options)

Can anybody guide me to any specific documentation link/work around so that I can overwrite/update image.

1

There are 1 answers

0
Celia On

Updating a file in GridFS is not possible. Each document is actually split into chunks and updating a file is not possible. Thus, I would suggest deleting the file you want to update first and after import the new one.

GridFSBucket gridFSBucket = GridFSBuckets.create(database, imageCollection);

GridFSBucket gridFSBucket = GridFSBuckets.create(database, imageCollection);
InputStream streamToUploadFrom = new FileInputStream(new File(new_image_file));

Document query = new Document("metadata.name", "image1");
MongoCursor<Document> cursor = database.getCollection(imagecollection+".files").find(query).iterator();

while (cursor.hasNext()) {
    Document document = cursor.next();
    Document metadata = document.get("metadata", Document.class);

    ObjectId _id = document.getObjectId("_id");
    gridFSBucket.delete(_id);

    GridFSUploadOptions options = new GridFSUploadOptions().metadata(metadata);
    ObjectId fileId = gridFSBucket.uploadFromStream("image1", streamToUploadFrom, options);
}