MongoDB Study Notes (5) MongoDB File Access Operations

Source: Internet
Author: User
Tags findone

Because MongoDB's document structure is BJSON format BJSON Full name: Binary JSON), and BJSON format itself supports saving data in Binary format, 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 supports the "GridFS" method. For file operations in the "GridFS" mode, a new assembly "MongoDB. GridFS. dll" must be introduced ". The following two methods are used for implementation.

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

 
 
  1. /// <Summary>
  2. /// Save the image to BJSON
  3. /// </Summary>
  4. Public void SaveImgBJSON (byte [] byteImg)
  5. {
  6. Document doc = new Document ();
  7. Doc ["ID"] = 1;
  8. Doc ["Img"] = byteImg;
  9. Collections collection. Save (doc );
  10. }

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

 
 
  1. /// <Summary>
  2. /// Obtain the byte data of the image stored in BJSON format
  3. /// </Summary>
  4. Public byte [] GetImgBJSON ()
  5. {
  6. Document doc = collections collection. FindOne (new Document {"ID", 1 }});
  7. Return doc ["Img"] as Binary;
  8. }

The above two pieces of code are added to the BLL encapsulation class for MongoDB-related operations. You can view the content in the previous section by using the encapsulation method. 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:

 
 
  1. protected void Button1_Click(object sender, EventArgs e)    
  2. {    
  3.     ImgBLL imgBll = new ImgBLL();    
  4.     imgBll.DeleteAll();    
  5.     imgBll.SaveImgBJSON(FileUpload1.FileBytes);    
  6.     Response.BinaryWrite(imgBll.GetImgBJSON());    
  7. }  

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

 
 
  1. Private string GridFsSave (byte [] byteFile)
  2. {
  3. String filename = Guid. NewGuid (). ToString ();
  4. // Here, the GridFile constructor has an overload. The bucket parameter is used to replace the default "fs" in the created set name.
  5. GridFile gridFile = new GridFile (relational database );
  6. Using (GridFileStream gridFileStream = gridFile. Create (filename ))
  7. {
  8. GridFileStream. Write (byteFile, 0, byteFile. Length );
  9. }
  10. Return filename;
  11. }
  12. Private byte [] GridFsRead (string filename)
  13. {
  14. GridFile gridFile = new GridFile (relational database );
  15. GridFileStream gridFileStream = gridFile. OpenRead (filename );
  16. Byte [] bytes = new byte [gridFileStream. Length];
  17. GridFileStream. Read (bytes, 0, bytes. Length );
  18. Return bytes;
  19. }
  20. Private void GridFsDelete (string filename)
  21. {
  22. GridFile gridFile = new GridFile (relational database );
  23. GridFile. Delete (new Document ("filename", filename ));
  24. }

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.

 
 
  1. /// <Summary>
  2. /// Save the image to GridFS
  3. /// </Summary>
  4. Public void SaveImgGridFS (byte [] byteImg)
  5. {
  6. String filename = GridFsSave (byteImg );
  7. Document doc = new Document ();
  8. Doc ["ID"] = 1;
  9. Doc ["filename"] = filename;
  10. Collections collection. Save (doc );
  11. }
  12. /// <Summary>
  13. /// Obtain images stored in GridFS Mode
  14. /// </Summary>
  15. Public byte [] GetImgGridFS ()
  16. {
  17. Document doc = collections collection. FindOne (new Document {"ID", 1 }});
  18. String filename = doc ["filename"]. ToString ();
  19. Return GridFsRead (filename );
  20. }

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.

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.