如何使用Java驱动程序3.7+获取单个GridFS文件?

时间:2019-03-24 21:47:18

标签: java mongodb

我需要使用Java驱动程序3.7+来获取GridFS文件。

我在数据库中有两个文件集:photo.filesphoto.chunks
photo.chunks集合包含二进制文件,如:

enter image description here

photo.files集合包含文档的元数据。 enter image description here

要使用我写的简单数据库查找文档:

 Document doc = collection_messages.find(eq("flag", true)).first();
 String messageText = (String) Objects.requireNonNull(doc).get("message");

根据屏幕上的收藏集,我试图以与上面的示例相同的方式查找文件并编写:

 MongoDatabase database_photos = mongoClient.getDatabase("database_photos");
 GridFSBucket photos_fs = GridFSBuckets.create(database_photos, 
 "photos");

 ...
 ...

 GridFSFindIterable gridFSFile = photos_fs.find(eq("_id", new ObjectId()));
 String file = Objects.requireNonNull(gridFSFile.first()).getMD5();

还有:

 GridFSFindIterable gridFSFile = photos_fs.find(eq("_id", new ObjectId()));
 String file = Objects.requireNonNull(gridFSFile.first()).getFilename();

但是我得到一个错误:

java.lang.NullPointerException
    at java.util.Objects.requireNonNull(Objects.java:203)
    at project.Bot.onUpdateReceived(Bot.java:832)
    at java.util.ArrayList.forEach(ArrayList.java:1249)

我也检查了3.7 driver的文档,但是此示例显示了如何查找多个文件,但我需要一个文件:

gridFSBucket.find().forEach(
  new Block<GridFSFile>() {
    public void apply(final GridFSFile gridFSFile) {
        System.out.println(gridFSFile.getFilename());
    }
});

有人可以给我示范一个如何正确实现的例子吗?
我的意思是获取数据,例如Object_id中的块收集中的{}和md5字段中Object_id中的md5字段中的数据预先感谢。

1 个答案:

答案 0 :(得分:0)

或者,我可以找到文件的特定字段。 可以首先创建第一个文件的objectId,然后将其传递到GridFSFindIterable对象,以从数据库中获取特定字段和值,最后获取文件以将其转换为String。

     MongoDatabase database_photos = 
     mongoClient.getDatabase("database_photos");
     GridFSBucket photos_fs = GridFSBuckets.create(database_photos, 
     "photos");
     ...
     ...
     ObjectId objectId = Objects.requireNonNull(photos_fs.find().first()).getObjectId();
     GridFSFindIterable gridFSFindIterable = photos_fs.find(eq("_id", objectId));
     GridFSFile gridFSFile = Objects.requireNonNull(gridFSFindIterable.first());
     String file =  Objects.requireNonNull(gridFSFile).getMD5();

但是它会检查来自photo.files的文件,而不是来自photo.chunks集合的文件。

enter image description here

由于调试信息,我不确定这种方式是否是代码安全的,但即使出现警告,它仍然可以工作:

Inconvertible types; cannot cast 'com.mongodb.client.gridfs.model.GridFSFile' to 'com.mongodb.client.gridfs.GridFSFindIterableImpl'

enter image description here

或者查找和使用特定文件:

photos_fs.find(eq("_id", objectId)).forEach(
(Block<GridFSFile>) gridFSFile -> {
// to do something 
});