1. 程式人生 > >.Net使用Mongodb增刪改查演示

.Net使用Mongodb增刪改查演示

類圖:

這裡寫圖片描述

Customer.cs實體類

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Bson;

namespace MongoDemo
{
    public class Customer
    {
        public ObjectId _id { get; set; }
        public ObjectId CustomerId { get; set
; } public string CustomerName { get; set; } public string ContactName { get; set; } public string Address { get; set; } public string PostalCode { get; set; } public string Telephone { get; set; } } }

CustomerHelper.cs

using System;
using System.Collections.Generic;
using
System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Driver; namespace MongoDemo { public class CustomerHelper { public static void Insert(Customer customer) { customer.CustomerId = new ObjectId(Guid.NewGuid().ToString("N"
)); // 首先建立一個連線 MongoClient mongo = new MongoClient(ConfigHelper.ConnectionString); var dataBase = mongo.GetDatabase(ConfigHelper.DataBaseName); // 根據型別獲取相應的集合 var collection = dataBase.GetCollection<Customer>("Customer"); // 向集合中插入物件 collection.InsertOne(customer); } public static void Delete(ObjectId customerId) { MongoClient mongo = new MongoClient(ConfigHelper.ConnectionString); var dataBase = mongo.GetDatabase(ConfigHelper.DataBaseName); var collection = dataBase.GetCollection<Customer>("Customer"); collection.DeleteOne(item => item.CustomerId == customerId); //唯一Id確保只刪除一條記錄 } /// <summary> /// 修改 /// </summary> /// <param name="customer"></param> public static void Update(Customer customer) { MongoClient mongo = new MongoClient(ConfigHelper.ConnectionString); var dataBase = mongo.GetDatabase(ConfigHelper.DataBaseName); var collection = dataBase.GetCollection<Customer>("Customer"); var filter = Builders<Customer>.Filter.Eq("CustomerId", customer.CustomerId); var update = Builders<Customer>.Update .Set("CustomerName", "騰訊科技") .Set("Telephone", "1389999999") .CurrentDate("lastModified"); collection.UpdateOne(filter, update); } public static List<Customer> Find(QueryDocument query) { MongoClient mongo = new MongoClient(ConfigHelper.ConnectionString); var dataBase = mongo.GetDatabase(ConfigHelper.DataBaseName); var collection = dataBase.GetCollection<Customer>("Customer"); List<Customer> list = collection.Find(query).ToList(); return list; } } }

UploadHelper.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Driver;
using MongoDB.Driver.GridFS;

namespace MongoDemo
{
    public class UploadHelper
    {
        /// <summary>
        /// 上傳檔案測試方法
        /// </summary>
        /// <returns></returns>
        public static bool Upload()
        {
            MongoServerSettings mongoSetting = new MongoServerSettings();
            mongoSetting.MaxConnectionPoolSize = 15000;//設定最大連線池
            mongoSetting.WaitQueueSize = 500;//設定等待佇列數
            mongoSetting.Server = new MongoServerAddress("192.168.1.176", 27017);
            MongoServer mongo = new MongoServer(mongoSetting);

            MongoGridFSSettings fsSetting = new MongoGridFSSettings() { Root = "DocPdf" };

            //例項化一個GridFS
            MongoGridFS gridfs = new MongoGridFS(mongo, ConfigHelper.DataBaseName, fsSetting);

            //將本地檔案上傳到mongoDB中去,以預設塊的大小256KB對檔案進行分塊
            gridfs.Upload("100100.pdf", "Test.pdf");
            return true;
        }

        public static void DownLoad()
        {
            MongoServerSettings mongoSetting = new MongoServerSettings();
            mongoSetting.MaxConnectionPoolSize = 15000;//設定最大連線池
            mongoSetting.WaitQueueSize = 500;//設定等待佇列數
            mongoSetting.Server = new MongoServerAddress("127.0.0.1", 27017);
            MongoServer mongo = new MongoServer(mongoSetting);

            MongoDatabase dataBase = mongo.GetDatabase(ConfigHelper.DataBaseName);
            MongoGridFSSettings fsSetting = new MongoGridFSSettings() { Root = "DocPdf" };


            //獲取檔案值
            string moFileName = "Test.pdf";
            //獲取圖片名
            //通過檔名去資料庫查值
            MongoGridFS fs = new MongoGridFS(dataBase, fsSetting);
            MongoGridFSFileInfo gfInfo = new MongoGridFSFileInfo(fs, moFileName);
            //方法一,很簡潔
            string fileName = Guid.NewGuid().ToString() + ".pdf";
            fs.Download(fileName, moFileName);
        }
    }
}

ConfigHelper.cs

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MongoDemo
{
    /// <summary>
    /// 初始化配置檔案資料
    /// </summary>
    public class ConfigHelper
    {
        /// <summary>
        /// MongoDb資料鏈連結地址
        /// </summary>
        public static string ConnectionString { get; set; }

        /// <summary>
        /// MongoDb資料庫
        /// </summary>
        public static string DataBaseName { get; set; }

        /// <summary>
        /// 初始化配置檔案資料
        /// </summary>
        public static void Init()
        {
            ConnectionString = ConfigurationManager.AppSettings["MongoDbServer"];
            DataBaseName = ConfigurationManager.AppSettings["DataBaseName"];

        }
    }
}

Program.cs

using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Driver.GridFS;

namespace MongoDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //初始化配置檔案
            ConfigHelper.Init();

            try
            {
                #region 插入資料測試(注意資料量是100W條)
                //int start = Environment.TickCount;
                //for (int index = 0; index < 1000000; index++)
                //{
                //    Customer customer = new Customer()
                //    {
                //        Address = "上海長寧區",
                //        ContactName = "0755-12345678",
                //        CustomerName = "上海動物園" + (index + 1).ToString(),
                //        PostalCode = "518000",
                //        Telephone = "1388888888888"
                //    };
                //    CustomerHelper.Insert(customer);
                //}
                //int end = Environment.TickCount;
                //Console.WriteLine("100000行資料處理耗時" + (end - start).ToString() + "ms");
                #endregion

                #region 更新
                //Customer customer = new Customer()
                //{
                //    Address = "深圳南山區",
                //    ContactName = "0755-12345678",
                //    CustomerName = "騰訊科技",
                //    PostalCode = "518000",
                //    Telephone = "1389999999",
                //    CustomerId = "c57e40ea343b4154ae3641e224525602"
                //};

                //CustomerHelper.Update(customer);
                #endregion


                #region 查詢
                //var query = new QueryDocument { { "CustomerName", "中科軟3" } };
                var query = new QueryDocument { { "CustomerId", new ObjectId("9cc11fa2aa7f400aba9a0649") } };
                var list = CustomerHelper.Find(query);
                #endregion

                CustomerHelper.Delete(new ObjectId("7f10ea7d8abf4c0285620f49"));



                MongoServerSettings mongoSetting = new MongoServerSettings();
                mongoSetting.MaxConnectionPoolSize = 15000;//設定最大連線池
                mongoSetting.WaitQueueSize = 500;//設定等待佇列數
                mongoSetting.Server = new MongoServerAddress("127.0.0.1", 27017);
                int count = MongoServer.MaxServerCount;
                MongoServer mongo=new MongoServer(mongoSetting);

                MongoDatabase dataBase = mongo.GetDatabase(ConfigHelper.DataBaseName);
                MongoGridFSSettings fsSetting = new MongoGridFSSettings() { Root = "DocPdf" };

                //例項化一個GridFS
                MongoGridFS gridfs = new MongoGridFS(dataBase, fsSetting);

                //將本地檔案上傳到mongoDB中去,以預設塊的大小256KB對檔案進行分塊
                //gridfs.Upload("100100.pdf", "Test.pdf");


                //獲取檔案值
                string moFileName = "Test.pdf";
                //獲取圖片名
                //通過檔名去資料庫查值
                MongoGridFS fs = new MongoGridFS(dataBase, fsSetting);
                MongoGridFSFileInfo gfInfo = new MongoGridFSFileInfo(fs, moFileName);
                //方法一,很簡潔
                string fileName = Guid.NewGuid().ToString() + ".pdf";
                fs.Download(fileName, moFileName);
                Console.ReadLine();

            }
            catch (Exception e)
            {

                throw;
            }
        }
    }
}

執行結果如圖:

(根據需要把註釋程式碼還原)
這裡寫圖片描述

這裡寫圖片描述

這裡寫圖片描述