MongoDB Learning Notes (v) MongoDB file access Operations

Source: Internet
Author: User
Tags file size findone mongodb

Because the document structure of MongoDB is in the Bjson format (bjson full name: Binary JSON), and the Bjson format itself supports data in binary format, you can save the data in binary format of the file directly into the MongoDB document structure. However, because the maximum length of a bjson cannot exceed 4M, it limits the maximum number of files that can be deposited in a single document beyond 4M. To provide support for bulk file access, the Samus driver provides a "GRIDFS" approach to support, and "Gridfs" mode file operations require the introduction of a new assembly "MongoDB.GridFS.dll". Here are two ways to implement each.

First, access files in the Document object

When the file size is small, directly into the document object to achieve more concise. For example, a large number of image file access, general picture files will not exceed 4M. We first implement an upload image into the database, and then take out to write back to the page example:

1. Save the picture in the Bjson

Copy Code code as follows:


///<summary>


///to save the picture in Bjson


///</summary>


public void Saveimgbjson (byte[] byteimg)


{


Document doc = new document ();


doc["ID" = 1;


doc["Img"] = byteimg;


Mongocollection.save (DOC);


}

2. Get image byte data stored in Bjson mode

Copy Code code as follows:


///<summary>


///Gets the image byte data stored in Bjson mode


///</summary>


public byte[] Getimgbjson ()


{


document doc= Mongocollection.findone (new document {{"ID", 1}});


return doc["IMG"] as Binary;


}


The above two pieces of code are two methods added to the BLL encapsulation class for MONGODB related operations to encapsulate the contents of the previous section. Here's a look at how to call in WebForm:

In the interface drag out a FileUpload control and a button control, page CS class plus the following methods:

Copy Code code as follows:


protected void Button1_Click (object sender, EventArgs e)


{


IMGBLL IMGBLL = new IMGBLL ();


Imgbll.deleteall ();


Imgbll.saveimgbjson (fileupload1.filebytes);


Response.BinaryWrite (Imgbll.getimgbjson ());


}

Second, the use of Gridfs way to access files

Before realizing the Gridfs way, I'll talk about its principle and why I can save large files. The driver first creates two collections in the current database: the "Fs.files" and "Fs.chunks" collections, which record file names, file creation times, file types, and other basic information, which blocks the binary data of the file (and supports encrypting the binary data). Chunking means dividing a file by a specified size and then depositing it into multiple documents. How does "fs.files" know which chunk of its corresponding file binary data is? That is because there is a "files_id" key in "Fs.chunks", which corresponds to the "_id" of "fs.files". "Fs.chunks" also has a key (int type) "n", which indicates the order of the blocks. The "FS" in the two collection names can also be customized by parameters.

If you just want to know how to use, you can ignore the above paragraph, the following will use:

1. Gridfs Way of File New, read, delete

Copy Code code as follows:


private String Gridfssave (byte[] bytefile)


{


string filename = Guid.NewGuid (). ToString ();





//Here The Gridfile constructor has an overload, and the bucket parameter is used to replace the default "FS" in the Create collection name.


gridfile gridfile = new Gridfile (mongodatabase);


using (Gridfilestream gridfilestream = gridfile.create (filename))


    {


Gridfilestream.write (bytefile, 0, bytefile.length);


    }


return filename;


}





Private byte[] Gridfsread (string filename)


{


gridfile gridfile = new Gridfile (mongodatabase);


Gridfilestream gridfilestream = gridfile.openread (filename);


byte[] bytes = new Byte[gridfilestream.length];


gridfilestream.read (bytes, 0, bytes. Length);


return bytes;


}





private void Gridfsdelete (string filename)


{


gridfile gridfile = new Gridfile (mongodatabase);


Gridfile.delete (New Document ("filename", filename));


}

2. Encapsulates the Gridfs operation again, the new document only stores the file name, equivalent to just a key, the new document can also have other than "filename" other keys.

Copy Code code as follows:


///<summary>


///to save the picture in Gridfs


///</summary>


public void Saveimggridfs (byte[] byteimg)


{


string filename = Gridfssave (byteimg);





Document doc = new document ();


doc["ID" = 1;


doc["filename"] = filename;


Mongocollection.save (DOC);


}





///<summary>


///Get the Gridfs way to store pictures


///</summary>


public byte[] Getimggridfs ()


{


Document doc = Mongocollection.findone (new Document {{"ID", 1}});


string filename = doc["filename"]. ToString ();


return gridfsread (filename);


}

Third, summary

File access should not be difficult, it is worth noting that when you read binary data from a document in the first way, be sure to convert the type to the "Binary" type, and the system's own key "_id", which is not a string type, is "Oid" type.

Author: Lee (Lipan)
Source: [Lipan] (http://www.cnblogs.com/lipan/)

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.