/* 使用mongoDB保存和管理的应用示例 建议mongod.cfg配置文件增加directoryPerDB: true,表示每个数据库均保存在独立同名文件夹中 # Where and how to store data. storage: dbPath: D:\Program Files\MongoDB\Server\6.0\data\db directoryPerDB: true journal: enabled: true 数据保存在myFiles数据库中。 示例: 新建集合 mongoTest.createCollection(String collectionName) 删除集合 mongoTest.deleteCollection(String collectionName) 把文档数据集(documents)保存到momgoDB的集合( colName) mongoTest.insertDocuments(String colName, List<Document> documents) 按文件名修改mongo数据中的文件编码 mongoTest.updateFileCode("FileTest","D:\\clx\\test.tt", "text:GBK"); 按查询条件filter删除colName集中中的数据 mongoTest.deleteData(String colName, Bson filter); 把保存在mongoDB的文件输出到本地 mongoTest.saveSelectDataToFile("FileTest", Filters.in("file_name", "DeleDFiles.py","iniModule.ini", "iniModule.py", "OpenDB.py")); mongoTest.saveSelectDataToFile("FileTest","D:\\clx\\test.tt"); //GBK文件 mongoTest.saveSelectDataToFile("FileTest","D:\\Python\\dict.txt");//大文件 查询列出存在mongoDB的数据 mongoTest.listSelectData("FileTest", "D:\\Python\\GD_Hydro_V0.7\\10_precision\\dj_03_gl_longchuan.txt"); mongoTest.listSelectData("FileTest", Filters.and( Filters.lt("file_size",1024), Filters.eq("file_ext","txt"))); mongoTest.listSelectData("FileTest", new Document( "file_code",FileToMongoDb.FILE_CODE_BUCTET).append("file_ext","xlsx")); ChenLX,2023.5.17 */ package mongo.gdsky.com.cn; import com.mongodb.MongoClient; import com.mongodb.MongoException; import com.mongodb.client.*; import com.mongodb.client.model.Filters; import org.bson.Document; import org.bson.conversions.Bson; import org.bson.types.Binary; import java.io.*; import java.util.List; //操作mongoDB数据库之文件数据 public class MongoDbFileUtil { private MongoDbConnection mongoConnection; private MongoClient mongoClient; private MongoDatabase database; // 用于演示接收输出文件的路径 private String FILE_OUTPUT_PATH = "D:\\temp"; //打开指定的数据库,并返回 public MongoDatabase openMongoDatabase(String databaseName) { mongoConnection = new MongoDbConnection(); //新建链接 mongoClient = mongoConnection.getConn(); //创建数据库对象 database = mongoClient.getDatabase(databaseName); return database; } //默认打开myFiles数据库 public MongoDatabase openMongoDatabase() { return openMongoDatabase("myFiles"); } //完成操作后请关闭 public void closeMongoDatabase() { mongoClient.close(); } public String getDatatbaseName() { return database.getName(); } //查询指定数据库中所有集合 public void selectCollection() { try { //查询Test数据库中所有集合名称 MongoIterable<String> colNameList = database.listCollectionNames(); for (String colName : colNameList) System.out.println(colName); System.out.println("[INFO] : Select collection success!"); } catch (MongoException e) { e.printStackTrace(); System.out.println("[ERROR] : Select collection fail!"); } } //新建集合 public void createCollection(String collectionName){ try{ //创建新集合 database.createCollection(collectionName); System.out.println("[INFO] : Create collection success!"); }catch(MongoException e){ e.printStackTrace(); System.out.println("[ERROR] : Create collection fail!"); } } //删除集合 public void deleteCollection(String collectionName){ try{ //删除集合 MongoCollection mongoCollection = database.getCollection(collectionName); mongoCollection.drop(); System.out.println("[INFO] : Drop collection success!"); }catch(MongoException e){ e.printStackTrace(); System.out.println("[ERROR] : Drop collection fail!"); } } //查询文档数据 public FindIterable<Document> selectData(String colName, Bson filter){ try{ //获取数据库中的集合,不存在就创建 MongoCollection<Document> collection = database.getCollection(colName); return collection.find(filter); //return collection.find(Filters.eq("file_path",fileName)); }catch(MongoException e){ e.printStackTrace(); System.out.println("[ERROR] : Select data fail!"); return null; } } public FindIterable<Document> selectData(String colName, String fileName){ return selectData(colName, new Document("file_path", fileName)); } /*查询并显示文档数据 参数:集合名、查询条件,例如:查询文件编码为大文件,文件后缀名为xlsx new Document("file_code", FileToMongoDb.FILE_CODE_BUCTET).append("file_ext","xlsx") 或 Filters.and( Filters.lt("file_size",1024), Filters.eq("file_ext","txt")) 如果是二进制方式保存的文本文件(文件编码以text开头),显示文件内容 */ public void listSelectData(String colName, Bson filter) { FindIterable<Document> iterable = selectData(colName, filter); if(iterable!=null){ //通过迭代器遍历找到的文档中的信息 int i=0; MongoCursor<Document> iterator = iterable.iterator(); while(iterator.hasNext()){ i++; Document doc=iterator.next(); System.out.println(doc.toJson()); //如果是文本文件,显示文件内容 String fileCode=doc.getString("file_code"); if(fileCode.startsWith(FileToMongoDb.FILE_CODE_TEXT)){ Binary fileBody= doc.get("file_body", Binary.class); try{ int len=FileToMongoDb.FILE_CODE_TEXT.length(); if(fileCode.length()>len) { fileCode=fileCode.substring(len+1,fileCode.length()); } else fileCode="UTF-8"; System.out.println( new String(fileBody.getData(), fileCode)); } catch(IOException e){ e.printStackTrace(); } } } System.out.println("[INFO] : Select data success!"+i); } } public void listSelectData(String colName, String fileName){ listSelectData(colName, Filters.eq("file_path",fileName)); } /* 把mongoDB数据document当作文件存到本地 参数:输出文件目录、mongo文档 根据编码格式,分三种方式保存到本地:二进制、大文件(超过4M)、文本方式 */ public long writeToFile(String outPath, Document document) { //如果不存在目录,创建目录 File file=new File(outPath); if(!file.exists()) file.mkdirs(); String fileName=file.getPath()+File.separator+document.get("file_name"); System.out.println("WriteToFile: "+document.toJson()); long len=(long)document.get("file_size"); String fileCode=document.get("file_code").toString(); //以二进制文件保存 if(FileToMongoDb.FILE_CODE_BINARY.equals(fileCode) || fileCode.startsWith(FileToMongoDb.FILE_CODE_TEXT)){ try{ Binary fileBody= document.get("file_body", Binary.class); FileOutputStream fos=new FileOutputStream(fileName); fos.write(fileBody.getData()); fos.close(); } catch (IOException e){ e.printStackTrace(); } } //大文件以bucket方式保存 else if(FileToMongoDb.FILE_CODE_BUCTET.equals(fileCode)) { MongoGridFS mongoGridFS=new MongoGridFS(); mongoGridFS.bucketToFile(outPath, document.getString("file_path")); } //以文本文件方式保存 else { File f=new File(fileName); try{ if(!f.exists()){ f.createNewFile(); } BufferedWriter bw=new BufferedWriter(new FileWriter(f)); bw.write(document.get("file_body").toString()); bw.close(); } catch (IOException e){ e.printStackTrace(); } } return len; } /*把查询结果存到本地文件 参数:集合名、查询条件,例如:查询文件编码为大文件,文件后缀名为xlsx new Document("file_code", FileToMongoDb.FILE_CODE_BUCTET).append("file_ext","xlsx") 获 Filters.eq("file_path",fileName) */ public void saveSelectDataToFile(String colName, Bson filter){ FindIterable<Document> iterable = selectData(colName, filter); if(iterable!=null){ //通过迭代器遍历找到的文档中的信息 int i=0; MongoCursor<Document> iterator = iterable.iterator(); while(iterator.hasNext()){ i++; writeToFile(FILE_OUTPUT_PATH, iterator.next()); } System.out.println("[INFO] : Select data success!"+i); } } /*把查询结果存到本地文件 参数:集合名、文件名(带目录路径) */ public void saveSelectDataToFile(String colName, String fileName){ //Document query=new Document("file_path",fileName); saveSelectDataToFile(colName, Filters.eq("file_path",fileName)); } /*把文档数据(document)保存到momgoDB的集合( colName) 参数:集合名、mongo文档 */ public void insertData(String colName, Document document){ try { MongoCollection mongoCollection = database.getCollection(colName); //一次插入一条数据 mongoCollection.insertOne(document); //System.out.println("[INFO] : Insert data success!"); }catch(MongoException e){ e.printStackTrace(); System.out.println("[ERROR] : Insert data fail!"); } } //插入多行数据 public void insertDocuments(String colName, List<Document> documents){ try { MongoCollection mongoCollection = database.getCollection(colName); //一次插入一条数据 mongoCollection.insertMany(documents); System.out.println("[INFO] : Insert documents success!"+documents.size()); }catch(MongoException e){ e.printStackTrace(); System.out.println("[ERROR] : Insert documents fail!"); } } /*按文件名修改mongo数据中的文件编码 参数:集合名、文件名(带目录)、文件编码 */ public void updateFileCode(String colName, String fileName, String code){ try { MongoCollection mongoCollection = database.getCollection(colName); //修改满足条件的第一条数据 //mongoCollection.updateOne(Filters.eq("file_path", fileName), // new Document("$set",new Document("file_code", code))); //修改满足条件的所有数据 {"$set",{keyname,newvalue}} mongoCollection.updateMany(Filters.eq("file_path", fileName), new Document("$set",new Document("file_code", code))); System.out.println("[INFO] : Update data success!"); }catch(MongoException e){ e.printStackTrace(); System.out.println("[ERROR] : Update data fail!"); } } /*删除数据 参数:集合名、查询条件 */ public void deleteData(String colName, Bson filter){ try { MongoCollection mongoCollection = database.getCollection(colName); //删除满足条件的第一条记录 //mongoCollection.deleteOne(Filters.eq("file_path",fileName)); //删除满足条件的所有数据 mongoCollection.deleteMany(filter); System.out.println("[INFO] : Delete data success!"); }catch(MongoException e){ e.printStackTrace(); System.out.println("[ERROR] : Delete data fail!"); } } public void deleteData(String colName, String fileName){ try { MongoCollection mongoCollection = database.getCollection(colName); //删除满足条件的第一条记录 mongoCollection.deleteOne(Filters.eq("file_path",fileName)); //删除满足条件的所有数据 mongoCollection.deleteMany(Filters.eq("file_path",fileName)); System.out.println("[INFO] : Delete data success!"); }catch(MongoException e){ e.printStackTrace(); System.out.println("[ERROR] : Delete data fail!"); } } public static void main(String args[]){ MongoDbFileUtil mongoTest =new MongoDbFileUtil(); //MongoDbConnection mongoDBConnection = new MongoDbConnection(); //新建链接 //MongoClient mongoClient = mongoDBConnection.getConn(); //创建数据库对象 //MongoDatabase mongoDatabase = mongoClient.getDatabase("myDB"); mongoTest.openMongoDatabase(); System.out.println("Current Database: "+mongoTest.getDatatbaseName()); //在Test里新建集合 //mongoTest.createCollection(mongoDatabase); //删除集合 //mongoTest.deleteCollection(mongoDatabase); //查询Test数据库中所有集合名称 mongoTest.selectCollection(); //修改数据 mongoTest.updateFileCode("FileTest", "D:\\Python\\GD_Hydro_V0.7\\.idea\\inspectionProfiles\\profiles_settings.xml", "text:UTF-8"); mongoTest.updateFileCode("FileTest","D:\\clx\\test.tt", "text:GBK"); //删除数据 //mongoTest.deleteData(mongoDatabase); //查询数据文档 mongoTest.listSelectData("FileTest", "D:\\Python\\GD_Hydro_V0.7\\10_precision\\dj_03_gl_longchuan.txt"); mongoTest.listSelectData("FileTest", Filters.and( Filters.lt("file_size",1024), Filters.eq("file_ext","txt"))); mongoTest.listSelectData("FileTest", new Document("file_code", FileToMongoDb.FILE_CODE_BUCTET).append("file_ext","xlsx")); mongoTest.listSelectData("FileTest","D:\\clx\\test.tt"); mongoTest.saveSelectDataToFile("FileTest", "D:\\Python\\DeleDFiles.py"); //文本文件示意 mongoTest.saveSelectDataToFile("FileTest", Filters.in( "file_name", "DeleDFiles.py","iniModule.ini", "iniModule.py", "OpenDB.py")); mongoTest.saveSelectDataToFile("FileTest","D:\\clx\\test.tt"); //GBK文件 mongoTest.saveSelectDataToFile("FileTest","D:\\Python\\dict.txt");//大文件 //关闭连接 mongoTest.closeMongoDatabase(); } }
mongoDB的针对文件的增删改查
最新推荐文章于 2024-11-16 09:37:16 发布