Java MongoDBがGridFSにファイルを追加する時、追加のパラメータフィールドを追加します。
2180 ワード
java白がまた来ました。ハハ。
今回の記録操作はmongodbのGridFSライブラリです。
ファイルを挿入した後、このDockmentに期限切れフィールドなどの他のフィールドを追加します。
直接コードの例:
今回の記録操作はmongodbのGridFSライブラリです。
ファイルを挿入した後、このDockmentに期限切れフィールドなどの他のフィールドを追加します。
直接コードの例:
/**
* MongoGridFS
* @param mac
* @param filenames (d:\77\77\hello.doc)
* @param expireat
* @return
*/
public static boolean uploadFilesByNames(MongoAttachConnect mac, Set filenames,Date expireat){
// MongoClient
MongoClient mongoClient = MongoClientBuild.GetMongoAttachClient(mac);
// MongoDatabase
MongoDatabase db = mongoClient.getDatabase(mac.BaseName);
AtomicBoolean isOK = new AtomicBoolean(true);
GridFSBucket gridFS = GridFSBuckets.create(db);
// Create some custom options
GridFSUploadOptions options = new GridFSUploadOptions();
filenames.forEach(filename->{
File f =new File(filename);
if(!f.exists()){
isOK.set(false);
return;
}
try {
//
String flame = f.getName();
// .pdf
String fileTye=flame.substring(flame.lastIndexOf("."),flame.length());
//
FileInputStream fileInputStream=new FileInputStream(f);
// filename ( )
//
Document metadata = new Document();
metadata.append("contentType", fileTye);
options.metadata(metadata);
//
gridFS.uploadFromStream(flame, fileInputStream,options);
/* - */
// update "$set"
Document update = new Document();
update.append("$set", new Document("expireAt", expireat));
// ,
db.getCollection("fs.files").updateOne(Filters.eq("filename",flame),update);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
});
return isOK.get();
}