如何在MongoDB GridFS中覆盖图像?

8

我使用的是MongoDB 3.2版本、Java 1.8版本以及mongo-java驱动程序。我已经将图像保存在数据库中了。我能够保存图像,读取图像和读取所有图像。现在我想更新GridFS中的图像。如果图像名称相同,我想要覆盖该图像。当我尝试使用相同名称保存图像时,会得到两张图片。我正在使用以下代码保存图像。

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)

请问是否有任何特定的文档链接或解决方法,可以帮助我覆盖或更新图片。

1个回答

4

在GridFS中无法更新文件。实际上,每个文档都被分成了多个块,因此无法更新文件。因此,我建议首先删除要更新的文件,然后再导入新文件。

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);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接