MongoDB supports multiple languages and is driven by multiple languages.
This blog mainly introduces how to MongoDB storage and read files premise: Download the corresponding driver: Official website download: http://central.maven.org/maven2/org/mongodb/mongo-java-driver/ I use mongo-2.10.1.jar version: MongoDB Operating Files, mainly through gridfs class. Storage files are mainly stored in FS, where FS is the default database.
Gridfs directly deals with databases and has nothing to do with collection sets. The specific operations are as follows:
Package COM. mongo. dao; import Java. io. file; import Java. util. list; import COM. mongoDB. basicdbobject; import COM. mongoDB. DB; import COM. mongoDB. dbobject; import COM. mongoDB. mongo; import COM. mongoDB. gridfs. gridfs; import COM. mongoDB. gridfs. gridfsdbfile; import COM. mongoDB. gridfs. gridfsinputfile;/*** use MongoDB to read files * @ author LHY **/public class gridfstest {public static void main (string [] ARGs) throws excep Tion {// SaveFile (); readfile () ;}/ *** storage file */public static void SaveFile () throws exception {// connect to the server Mongo = new Mongo (); // connect to the database DB = Mongo. getdb ("testgridfs"); // file operations are implemented on the basis of dB, and there is no relationship with tables and documents. gridfs = NULL; gridfs = new gridfs (db ); string filename = "vltest. log "; file readfile = new file (" D:/"+ filename); gridfsinputfile contains file = gridfs. createfile (readfile); // you can add another attribute named file. put ("path", "d :/"+ Filename); // save your file. save ();}/*** read the file, read the disk * @ throws exception */public static void readfile () throws exception {// linked to the server Mongo = new Mongo (); // connect to the database DB = Mongo. getdb ("testgridfs"); gridfs = NULL; gridfs = new gridfs (db); // query condition dbobject query = new basicdbobject (); // query result: list <gridfsdbfile> listfiles = gridfs. find (query); gridfsdbfile griddbfile = listfiles. get (0); // get the file name // Note: it is not the column name of the table in FS, but the string filename = (string) griddbfile according to the property in the debug griddbfile. get ("FILENAME"); system. out. println ("get the file name from MongoDB:" + filename); file writefile = new file ("D:/" + filename); If (! Writefile. exists () {writefile. createnewfile ();} // write data to the disk // view the corresponding prompt griddbfile. writeto ("D:/a.txt"); // write griddbfile to the file. writeto (writefile );}}
Images are stored as files. The result of running the above storage is as follows: