1024programmer Mongodb MongoDB study notes (5) MongoDB file access operation

MongoDB study notes (5) MongoDB file access operation

Because the document structure of MongoDB is BJSON format (BJSON full name: Binary JSON), and BJSON format itself supports saving data in binary format, so you can put The data in the binary format of the file is saved directly into the MongoDB document structure. However, since the maximum length of a BJSON cannot exceed 4M, the maximum file that can be stored in a single document cannot exceed 4M. In order to provide support for large-capacity file access, the samus driver provides “GridFS” mode to support, and “GridFS” mode file operations need to introduce a new assembly “MongoDB.GridFS.dll”. Below we implement it in two ways.

 

1. Access files in the document object

When the file size is small, it is simpler to implement directly into the document object. For example, the access of a large number of picture files, etc., the general picture files will not exceed 4M. Let’s implement an example of uploading pictures and storing them in the database, and then taking them out and writing them back to the page:

1. Save the picture in BJSON


///

/// Save the picture in BJSON
///

public void SaveImgBJSON(byte[] byteImg)
{
Document doc = new Document();
doc[“ID”] = 1;
doc[“Img”] = byteImg;
mongoCollection. Save(doc);
}
2. Obtain the image byte data stored in BJSON mode

///

/// Get the image byte data stored in BJSON
///

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 in the BLL encapsulation class for MongoDB-related operations. See the previous section for the encapsulation method. Let’s see how to call it in webform:

Drag out a FileUpload control and a Button control on the interface, and add the following method to the cs class of the page:


protected void Button1_Click(object sender, EventArgs e)
{
ImgBLL imgBll = new ImgBLL();
imgBll. DeleteAll();
imgBll.SaveImgBJSON(FileUpload1.FileBytes);
Response.BinaryWrite(imgBll.GetImgBJSON());
}
2. Use GridFS to access files

Before implementing the GridFS method, let me talk about its principle and why large files can be stored. The driver will first create two collections in the current database: “fs.files” and “fs.chunks” collections, the former records basic information such as the file name, file creation time, file type, etc.; the latter stores the binary data of the file in chunks (and supports encrypting these binary data). Chunking means to divide the file according to the specified size, and then store it in multiple files. How does “fs.files” know which blocks its corresponding file binary data is in? That’s 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 sequence of these chunks. The “fs” in these two collection names can also be customized by parameters.

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

1. Create, read and delete files in GridFS mode

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 created 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. Encapsulate the GridFS operation again. The new document only stores the file name, which is equivalent to just a key. The new document can also have other keys besides “file name”.


///

/// Save the picture to GridFS
///

public void SaveImgGridFS(byte[] byteImg)
{
  string filename = GridFsSave(byteImg);

Document doc = new Document();
doc[“ID”] = 1;
doc[“filename”] = filename;
mongoCollection. Save(doc);
}

///

/// Get the image stored in GridFS
///

public byte[] GetImgGridFS()
{
Document doc = mongoCollection. FindOne(new Document { { “ID”, 1 } });
String filename = doc[“filename”].ToString();
return GridFsRead(filename);
}
3. Summary

File access should not be very difficult. It is worth noting that: when using the first method to read binary data from the document, the type must be converted to “Binary” type; there is also the key “_id” that comes with the system, It is also not of type string, it is of type “Oid”.

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/mongodb-study-notes-5-mongodb-file-access-operation/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索