MongoDB Study Notes (5) MongoDB File Access Operations

Source: Internet
Author: User
Tags findone

Because MongoDB's document structure is in bjson format (bjson Full name: Binary JSON), bjson itself supports storing binary data, therefore, the binary data of the file can be directly stored in the document structure of MongoDB. However, because the maximum length of a bjson file cannot exceed 4 MB, the maximum size of files that can be stored in a single document cannot exceed 4 MB. To provide support for large-capacity file access, the samus Driver provides the "gridfs" method. The "gridfs" method requires the introduction of newProgramSet "MongoDB. gridfs. dll ". The following two methods are used for implementation.

Series directory

MongoDB Study Notes (1) Introduction and installation of MongoDB
MongoDB Study Notes (2) use the samus driver to perform basic data operations
MongoDB learning notes (3) using jqgrid tables to operate MongoDB data in MVC Mode
MongoDB learning notes (4) describe the data relationship using the document structure of MongoDB
MongoDB Study Notes (5) MongoDB File Access Operations
MongoDB Study Notes (6) MongoDB index usage and Efficiency Analysis

1. access a file in a Document Object

When the file size is small, it is simpler to directly store the file object. For example, the access to a large number of image files is generally not more than 4 MB. The following example shows how to store an uploaded image to a database and write it back to the page:

1. Save the image to bjson

/// <Summary> /// Save the image to bjson /// </Summary> Public void saveimgbjson (byte [] byteimg) {document DOC = new document (); doc ["ID"] = 1; Doc ["IMG"] = byteimg; your collection. save (DOC );}

2. Obtain the byte data of images stored in bjson format

 
/// <Summary> /// obtain the byte data of the image stored in bjson format. // </Summary> Public byte [] getimgbjson () {document DOC = Invalid collection. findone (new document {"ID", 1}); Return Doc ["IMG"] as binary ;}

The above two paragraphsCodeThis is the two methods added to the BLL encapsulation class for MongoDB-related operations. You can view the content of the previous section in the encapsulation mode. The following describes how to call webform:

Drag a fileupload control and a button control on the interface. Add the following method to the CS class on the page:

Protected void button1_click (Object sender, eventargs e) {imgbll = new imgbll (); imgbll. deleteall (); imgbll. saveimgbjson (fileupload1.filebytes); response. binarywrite (imgbll. getimgbjson ());}
2. Access files through gridfs

Before implementing the gridfs method, let's talk about its principle and why it can store large files. The driver first creates two sets in the current database: "FS. files "and" FS. chunks "set. The former records basic information such as the file name, File Creation Time, and file type. The latter stores binary data of the file in blocks (and supports encryption of these binary data ). Multipart refers to splitting the file according to the specified size and then saving it to multiple documents. "Fs. Files": How do you know the binary data of the corresponding file? That's because there is a "files_id" key in "fs. chunks", which corresponds to "_ id" of "fs. Files ". "Fs. chunks" also has a key (INT type) "N", which indicates the order of these blocks. The "FS" in the two collection names can also be customized by parameters.

If you just want to know how to use it, you can ignore the above section and use it as follows:

1. Create, read, and delete gridfs files

Private string gridfssave (byte [] bytefile) {string filename = guid. newguid (). tostring (); // here, the gridfile constructor has an overload. The bucket parameter is used to replace the default "FS" in the created set name. Gridfile = new gridfile (relational database); Using (gridfilestream = gridfile. create (filename) {gridfilestream. write (bytefile, 0, bytefile. length);} return filename;} private byte [] gridfsread (string filename) {gridfile = new gridfile (relational database); gridfilestream = gridfile. openread (filename); byte [] bytes = new byte [gridfilestream. length]; gridfilestream. read (bytes, 0, bytes. length); Return bytes;} private void gridfsdelete (string filename) {gridfile = new gridfile (relational database); gridfile. delete (new document ("FILENAME", filename ));}

2. Re-encapsulate the gridfs operation. The new file only stores the file name, which is equivalent to a key. The new file can also have a key other than the "file name.

/// <Summary> /// Save the image to gridfs /// </Summary> Public void saveimggridfs (byte [] byteimg) {string filename = gridfssave (byteimg ); document Doc = new document (); Doc ["ID"] = 1; Doc ["FILENAME"] = filename; invalid collection. save (DOC);} // <summary> // obtain the image stored in gridfs mode. // </Summary> Public byte [] getimggridfs () {document DOC = Invalid collection. findone (new document {"ID", 1}); string filename = Doc ["FILENAME"]. tostring (); Return gridfsread (filename );}
Iii. Summary

File access should not be difficult. It is worth noting that when reading binary data from the document in the first way, the type must be converted to the "binary" type; there is also the built-in key "_ id", which is not of the string type and is of the "oid" type.

By Lipan)
Source: [Lipan] (http://www.cnblogs.com/lipan)
Copyright: The copyright of this article is shared by the author and the blog. The detailed link of this article must be noted during reprinting; otherwise, the author will be held legally liable.
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.