As a NoSql database representative, access to multimedia data, should be a strength, right? So how are images accessed in mongoDB? (In fact, relational databases have no problem accessing images at all, so I think NoSql’s strength is not in storing multimedia, but in using key-value pairs to store data.)

\

MongoDB can access images in two ways:

“MongoDB document structure is in BJSON format (full name: Binary JSON), and THE BJSON format itself supports storing Binary data, so the Binary file data can be directly saved to the MongoDB document structure. However, since the maximum length of a BJSON file cannot exceed 4M, the maximum size that can be stored in a single document is limited to 4M. To support large file access, the Samus driver provides a “GridFS” mode to support file operation, which requires the introduction of a new assembly “mongodb.gridfs.dll”.

\

Accessing files in a Document Object When the file size is small, direct saving to a document object is simpler to implement. For example, access to a large number of picture files, etc., the general picture files are not more than 4M. Let’s implement an example of uploading an image to the database and then writing it back to the page: \

\

\

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.IO;

using MongoDB.Bson;
using MongoDB.Driver;

namespace mongotest
{
    public partial class Form3 : Form
    {
        public Form3()
        {
            InitializeComponent();
            Init();
        }
        // Database connection string
        const string strconn = "Mongo: / / 127.0.0.1:27017";
        // Database name
        const string dbName = "test";
        MongoServer server;
        MongoDatabase db;
        void Init()
        {
            // Create a database link
            server = MongoDB.Driver.MongoServer.Create(strconn);
            // Get the database
            db = server.GetDatabase(dbName);
        }
        private void SaveImgBJSON(byte[] byteImg)
        {
            BsonDocument doc = new BsonDocument();

            doc["ID"] = 1;
            doc["Img"] = byteImg;

            MongoCollection col = db.GetCollection("thins");
            col.Save(doc);
        }
        private void btnSaveImg_Click(object sender, EventArgs e)
        {
            byte[] byteImg = File.ReadAllBytes(@"c:\temp\yl.jpg");
            SaveImgBJSON(byteImg);
        }
        private void btnShowImg_Click(object sender, EventArgs e)
        {
            MongoCollection col = db.GetCollection("thins");
            var query = new QueryDocument { { "ID".1}};var result = col.FindAs<BsonDocument>(query);
            byte[] buff = (byte[])((BsonDocument)result.ToList()[0]).GetValue("Img");
            MemoryStream MS = newMemoryStream(buff); pictureBox1.Image = Image.FromStream(MS); }}}Copy the code

Before implementing GridFS, LET me explain how it works and why it is possible to store large files. The driver first creates two collections in the current database: “fs.files” and “fs.chunks”. The former contains basic information about the file name, creation time, and file type. The latter blocks the binary data of the file (and supports encryption of the binary data). Chunking means dividing a file into a specified size and storing it in multiple documents. Fs.files “how do I know what block of binary data it corresponds to? That is because there is a “files_id” key in “fs.files” which corresponds to the “_id” of “fs.files”. Fs.chunks “also has a key (int)”n” that indicates the sequence of these chunks. The “fs” in these two collection names is also customizable with parameters. (I think of Sql Server FileStream)

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

Here cites two third-party DLL, can go to https://github.com/samus/mongodb-csharp to download and compiled.

\

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.IO;

using MongoDB;
using MongoDB.GridFS;

namespace mongotest
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
            Init();
        }
        private void btnGridFSSave_Click(object sender, EventArgs e)
        {
            byte[] byteImg = File.ReadAllBytes(@"c:\temp\yl.jpg");
            filename = GridFsSave(byteImg);
            MessageBox.Show(filename);
        }
        private void btnGridFSShow_Click(object sender, EventArgs e)
        {
            byte[] buff = GridFsRead(filename);
            MemoryStream MS = new MemoryStream(buff);
            pictureBox1.Image = Image.FromStream(MS);
        }
        private Mongo mongo;
        private IMongoDatabase test;
        string filename;
        void Init()
        {
            var connstr = @"Server=localhost:27017";
            mongo = new Mongo(connstr);
            mongo.Connect();
            test = mongo["test"];
        }
        private string GridFsSave(byte[] byteFile)
        {
            string filename = Guid.NewGuid().ToString();

            // The GridFile constructor has an overload, and the bucket argument is used to replace the default "fs" in the creation collection name.
            GridFile gridFile = new GridFile(test);
            using (GridFileStream gridFileStream = gridFile.Create(filename))
            {
                gridFileStream.Write(byteFile, 0, byteFile.Length);
            }
            return filename;
        }
        private byte[] GridFsRead(string filename)
        {
            GridFile gridFile = new GridFile(test);
            GridFileStream gridFileStream = gridFile.OpenRead(filename);
            byte[] bytes = new byte[gridFileStream.Length];
            gridFileStream.Read(bytes, 0, bytes.Length);
            returnbytes; }}}Copy the code

\

Stored in the database as shown below:

\

\

Reference article:

www.cnblogs.com/lipan/archi…