MongoDB makes a crud operation of pictures--in combination with Java

Source: Internet
Author: User
Tags findone readfile

The last few blogs simply introduced MongoDB and how to install it, and how to operate MongoDB under DOS and what errors occurred in the installation of MongoDB, how to solve it. Of course, these are not enough, we have to use the actual. I did a simple demo with myeclipse+jdk1.7 to show how MongoDB can be used in practice.

MongoDB as a representative of a NoSQL database, access to multimedia data, should be the strength of it? So, how does a crud operation in MongoDB work on a picture?

As already mentioned in several blogs, MongoDB's document structure is Bson format, the Bson format natively supports saving binary format data, so you can save data in binary format of file directly into MONGODB document structure. However, the maximum length of a bson cannot exceed 4M, so limiting the maximum number of files that can be deposited in a single document cannot exceed 4M. To solve this problem, MongoDB provides a "Gridfs" approach, and the "Gridfs" approach to file operations requires the introduction of the relevant JAR package--mongo-java-driver-2.9.3.jar.

Not much to say, see Example:

Package Com.zd.mongodb.common;import Java.io.file;import Java.io.ioexception;import java.net.UnknownHostException; Import Com.mongodb.db;import com.mongodb.dbcollection;import Com.mongodb.dbobject;import Com.mongodb.Mongo;import Com.mongodb.gridfs.gridfs;import Com.mongodb.gridfs.gridfsdbfile;import Com.mongodb.gridfs.GridFSInputFile; public class Mongodbcommon {//Connection Mongodbpublic DB mongodbconnection () {Mongo m = null;try {m = new Mongo ("localhost", 2701 7);} catch (Unknownhostexception e) {e.printstacktrace ();} DB db = M.getdb ("test"); return db;}  Save picture Information public void SaveFile (string connection, string ID, string file) {db db = Mongodbconnection (); Get the database for MongoDB file ImageFile = new file (file); Gridfs Gfsphoto = new Gridfs (db, connection); Connection is a set noun gridfsinputfile gfsfile = null;try {gfsfile = Gfsphoto.createfile (ImageFile);} catch (IOException e) {E . Printstacktrace ();} Gfsfile.setid (ID); Gfsfile.setcontenttype ("Image/jpeg"); Gfsfile.save ();} Read file public void ReadFile (String connectIon, String FileName) {db db = Mongodbconnection ();  Get connection Dbcollection collection = Db.getcollection (connection); Connection is the collection name string newfilename = FileName; Gridfs Gfsphoto = new Gridfs (db, connection); Gridfsdbfile imageforoutput = Gfsphoto.findone (NewFileName);   System.out.println (Imageforoutput); <span style= "font-family:arial, Helvetica, Sans-serif;" >//returns data in Bson format </span>}//query the corresponding file based on id public void Findbyobjectid (string connection, string id) {db db = Mongodbconnection ();D bcollection collection = db.getcollection (connection);D bobject dbobj = collection.findone (ID);  System.out.println (Dbobj); Returns data in Bson format}//delete file public void DeleteFile (String connection,string ID) {DB db = Mongodbconnection ();D bcollection Collection = Db.getcollection (connection);D bobject o=collection.findone (ID); Collection.remove (o);}}


Client:

Package Com.zd.mongodb.common;public class Zhudantest {<span style= "White-space:pre" ></span><span Style= "White-space:pre" ></span> public static void Main (string[] args) throws Exception {<span style= " White-space:pre "></span> Mongodbcommon dbcommon=new Mongodbcommon (); <span style=" White-space:pre "> </span> string Newfilename= "zhudan.jpg"; <span style= "White-space:pre" ></span>     string Imagefile= "d:/Life/Photo/me/zhudan.jpg";//<span style= "White-space:pre" ></span>     String Connection= "Photo.files"; <span style= "White-space:pre" ></span>     String connection= "Photo"; <span style= "White-space:pre" ></span>     <span style= "White-space:pre" ></span >    //save data by ID <span style= "white-space:pre" ></span>     String id= "1111"; <span Style= "White-space:pre" ></span>     Dbcommon.savefile (connection, ID, ImageFile); <span style= "White-space:pre" ></span>     <span style= "White-space:pre" ></span>    //Get data by name//<span style= "White-space:pre" ></span> dbcommon.readfile ( connection, newfilename); <span style= "White-space:pre" ></span>     <span style= " White-space:pre "></span>    //delete data by ID//<span style=" white-space:pre "></span>     String id= "1111";//<span style= "White-space:pre" ></span>     Dbcommon.deletefile ( Connection,id) <span style= "White-space:pre" ></span> <span style= "White-space:pre" ></ span>    //query data by ID//<span style= "white-space:pre" ></span> String id= "1111";//<span Style= "White-space:pre" ></span> Dbcommon.findbyobjectid (connection, id); <span style= "White-space:pre" ></span> <span style= "White-space:pre" ></span>}}

Take the picture as proof:

The principle of re-analysis:

When you create a photo, the driver first creates two collections in the current database: One is the "Photo.files" collection and the other is the "Photo.chunks" collection, which records basic information such as file name, file creation time, file type, and so on. The latter block stores the binary data of the file (and supports the encryption of these binary data).

A trunk has a default size, when the file exceeds this default size, the file will be divided into multiple chunk, and then save the chunk to Photo.chunks, and finally the file information into the photo.files.

When reading the file, according to the query criteria, find a suitable record in the Photo.files, get the value of "_id", and then according to this value to Photo.chunks to find all "files_id" to "_id" chunk, and by "n" to sort, Finally, read the contents of the "data" object in chunk, and revert to the original file.

Speaking of principle,In the course of my testing, when I save the picture, I need to use the collection name is photo, when I read and delete the picture, I need to use the full set name is Photo.files. If I don't have a collection name at this point, I can't find the relevant data.

Summarize:

MongoDB as a representative of a NoSQL database, in fact, it contains a lot of things, I have access to only the tip of the iceberg, for the future of MongoDB learning to do a little preparation.




MongoDB makes a crud operation of pictures--in combination with Java

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.