MongoDB is a non-relational database (NOSQL) that implements object-oriented thinking (Oo thought), and each record in MONGO DB is a document object. The biggest advantage of Mongo DB is that all data persistence requires no developers to write SQL statements manually, and it is easy to invoke methods to implement CRUD operations.
This blog mainly describes how MongoDB stores and read files.
MongoDB operations files, mainly through the Gridfs class. The storage file is primarily stored in FS, where FS is the default for the database. And Gridfs is dealing directly with the database, regardless of the collection collection.
Since MongoDB's document structure is Bjson format (bjson full name: Binary JSON), and the Bjson format natively supports the preservation of binary format data, it is possible to save data in the binary format of the file directly into the MongoDB document structure. However, since the maximum length of a bjson cannot exceed 4M, it limits the maximum number of files that can be deposited in a single document to no more than 4M. To provide support for large-capacity file access, the Samus driver provides a "Gridfs" way to support it.
Method Code:
/** * Store Files *@param CollectionName Collection Name *@param file Files *@param fileid File ID *@param the company ID of the CompanyID file *@param filename File name */PublicvoidSaveFile (string collectionname, File file, string Fileid, String CompanyID, string filename) {try {db db = Mongotemplate.getdb ();Storage FS root node Gridfs Gridfs =New Gridfs (DB, CollectionName); Gridfsinputfile GFs = gridfs.createfile (file); Gfs.put ("Aliases", CompanyID); Gfs.put ("FileName", Fileid); Gfs.put ("ContentType", Filename.substring (Filename.lastindexof (catch (Exception e) {e.printstacktrace (); System.out.println (" An error occurred while storing the file!!! "); } } //take out file public gridfsdbfile Retrievefileone (string collectionname, string filename) {try {db db = Mongotemplate.getdb () ; //get the root node of fs Gridfs Gridfs = new gridfs (db, CollectionName); Gridfsdbfile dbfile = gridfs.findone (filename); if (dbfile! = null) {return dbfile ; }} catch (Exception e) {//todo:handle Exception} return null;}
MongoDB Access picture file features