
이 저작물은 크리에이티브 커먼즈 저작자표시-동일조건변경허락 2.0 대한민국 라이선스에 따라 이용할 수 있습니다.
//클라이언트 연결
MongoClient client = new MongoClient("localhost");
//데이터베이스 선택
MongoDatabase database = client.getDatabase("tutorial");
//컬렉션 선택
MongoCollection<Document> collection = database.getCollection("numbers");
//GridFS가 생성될 컬렉션 이름
final String bucket = "test";
//GridFS를 이용해 저장할 파일명
final String filename = "test.JPG";
//bucket명으로 지정한 GridFS연결 생성
GridFSBucket gridFSBucket = GridFSBuckets.create(database,bucket);
//사용자 정의 metadata에 저장될 샘플 BsonDocument
ObjectId etag = new ObjectId();
BsonDocument metadata = new BsonDocument();
metadata.put("_etag", new BsonObjectId(etag));
GridFSUploadOptions options = new GridFSUploadOptions().metadata(Document.parse(metadata.toJson()));
//GridFS를 이용해 저장할 파일 InputStream 생성
InputStream sourceStream = MongoConnector.class.getResourceAsStream(filename);
//GridFS를 이용해 파일 저장 후 _id값 받아오기
ObjectId _id = gridFSBucket.uploadFromStream( filename, sourceStream, options);
//저장된 _id값 출력
System.out.println(_id);
//생성된 GridFS 컬렉션 확인
> show tables;
numbers
test.chunks
test.files
//생성된 chunk 수 확인
> db.test.chunks.count()
25
//저장된 file 정보 확인
> db.test.files.find().pretty()
{
"_id" : ObjectId("58477396f034dd1b840b32d4"),
"filename" : "test.JPG",
"length" : NumberLong(6341811),
"chunkSize" : 261120,
"uploadDate" : ISODate("2016-12-07T02:27:35.304Z"),
"md5" : "48b2a854b5deb75370fcaaef52c865e6",
"metadata" : {
"_etag" : ObjectId("58477396f034dd1b840b32d3")
}
}
>
//bucket명으로 지정한 GridFS연결 생성
GridFSBucket downloadGridFs = GridFSBuckets.create(database,bucket);
//지정된 파일명에 해당하는 id가져오기
ObjectId fid = downloadGridFs.find(Filters.eq("filename", filename)).first().getObjectId();
//가져온 파일을 d:/mongo.JPG에 저장
downloadGridFs.downloadToStream(fid, new FileOutputStream(new File("d:/mongo.JPG")));