I have two GridFS collections in my mongo db, I need to transfer the files from one GridFS collection to another collection in the same db.
I have a List that I'm using with $in operator to get a list of files which is returned as GridFSFindIterable, now I need to find a way to move these GridFSFiles to the new collection bucket2.
GridFSBucket bucket1= GridFSBuckets.create(db, "bucket1");
GridFSBucket bucket2= GridFSBuckets.create(db, "bucket2");
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("_id", new BasicDBObject("$in", fileIdsList));
GridFSFindIterable bucket1Files = bucket1.find(searchQuery);
for(GridFSFile file: bucket1Files){
}
What is the best approach to store these list of files in bucket2 collection?
So I solved this issue in a simple way. Instead of getting the gridFSBucket and GridFSFile and trying to migrate that to the new collection which complicated evertything, I just decided to run find() method on the mongoCollections bucket1.files and bucket1.chunks directly.
This returns the List documentsList which you can insert into bucket2.files and bucket2.chunks
I tested it and the images I uploaded in bucket1 can be retrieved from the new collection bucket2 after following this process.
MongoCollection<Document> bucket1FileColl = db.getCollection("bucket1.files");
MongoCollection<Document> bucket1ChunkColl = db.getCollection("bucket1.chunks");
MongoCollection<Document> bucket2FileColl = db.getCollection("bucket2.files");
MongoCollection<Document> bucket2ChunkColl = db.getCollection("bucket2.chunks");
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("_id", new BasicDBObject("$in", attachmentFileIdsList));
ArrayList<Document> bucket1Files=
bucket1FileColl.find(searchQuery).into(new ArrayList<Document>());
if(CollectionUtils.isNotEmpty(bucket1Files)){
bucket2FileColl.insertMany(bucket1Files);
}
BasicDBObject searchQueryChunks = new BasicDBObject();
searchQueryChunks.put("files_id", new BasicDBObject("$in", attachmentFileIdsList));
ArrayList<Document> bucket1Chunks= bucket1ChunkColl.find(searchQueryChunks).into(new ArrayList<Document>());
if(CollectionUtils.isNotEmpty(bucket1Chunks)){
bucket2ChunkColl.insertMany(bucket1Chunks);
}