MongoDB GridFS 文件系统
实战演练
1.通过--help选项,查看mongofile的帮助文档

2.通过mongofile -h {ip:port} -d {collectionName} put {fileName}

其中-h选项指定主机名以及端口号,-d选项指定数据库名,put操作即为添加文件至MongoDB。
3.
4.GridFS在数据库中,默认使用fs.chunks和fs.files来存储文件。
其中fs.files集合存放文件的信息,fs.chunks存放文件数据



list:获取文件列表
get:获取文件
delete:删除文件
search:查询文件
7.通过Java Driver操作MongoDB
【网友实现】MongoDB GridFS 文件系统
public class GridfsDemon{
public static void main(String[] args) {
// TODO Auto-generated method stub
String URL = "192.168.136.138:27017";
MongoClient mongoClient = new MongoClient(URL);
DB db = mongoClient.getDB("jike");
GridFS gridFS = new GridFS(db);
File file = new File(System.getProperty("user.home") + "/MongoDB-manaul.pdf");
try {
// 存文件
FileInputStream fileInputStream = new FileInputStream(file);
GridFSInputFile createFile = gridFS.createFile(fileInputStream);
createFile.put("fileName", "MongoDB_manual_3.0_2.pdf");
createFile.put("contentType", "application/pdf");
createFile.save();
// 取文件
GridFSDBFile findOne = gridFS.findOne(new BasicDBObject("_id", createFile.getId()));
System.out.println(findOne);
// 取文件列表
DBCursor fileList = gridFS.getFileList();
while(fileList.hasNext()){
System.out.println(fileList.next());
}
// 删除文件
gridFS.remove(new BasicDBObject("_id",createFile.getId()));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
mongoClient.close();
}
}
}

由上图可见,通过java driver文件成功上传至MongoDB中。
网友评论