Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overwrite image in mongoDB gridfs?

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.

like image 918
Vishwas Avatar asked Dec 19 '16 13:12

Vishwas


1 Answers

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);
}
like image 175
Celia Avatar answered Sep 29 '22 09:09

Celia