主頁 > 知識(shí)庫 > MongoDB入門教程之C#驅(qū)動(dòng)操作實(shí)例

MongoDB入門教程之C#驅(qū)動(dòng)操作實(shí)例

熱門標(biāo)簽:兗州電話外呼營銷系統(tǒng) 企業(yè)智能外呼系統(tǒng)價(jià)格多少 高德地圖標(biāo)注商戶位置 徐州ai電銷機(jī)器人原理 智能電銷機(jī)器人銷售話術(shù) 南京400電話怎樣辦理 福州電銷機(jī)器人源代碼 沈陽營銷電銷機(jī)器人招商 機(jī)器人外呼系統(tǒng)軟件存在問題

作為系列的最后一篇,得要說說C#驅(qū)動(dòng)對mongodb的操作,目前驅(qū)動(dòng)有兩種:官方驅(qū)動(dòng)和samus驅(qū)動(dòng),不過我個(gè)人還是喜歡后者,

因?yàn)樘峁┝素S富的linq操作,相當(dāng)方便。

官方驅(qū)動(dòng):https://github.com/mongodb/mongo-csharp-driver/downloads。下載后,還提供了一個(gè)酷似msdn的幫助文檔。

samus驅(qū)動(dòng):https://github.com/samus/mongodb-csharp/downloads。

下面就具體看看samus驅(qū)動(dòng),https://github.com/samus/mongodb-csharp/blob/master/examples/Simple/Main.cs上面提供了

一個(gè)簡單的demo,大體上看看我們就知道怎么玩了。

一: 實(shí)踐

1:我們建立一個(gè)Person實(shí)體,MongoAlias特性表示取別名,這里的ID值將會(huì)覆蓋掉數(shù)據(jù)庫自動(dòng)生成的_id。

復(fù)制代碼 代碼如下:

#region 數(shù)據(jù)實(shí)體
    /// summary>
/// 數(shù)據(jù)實(shí)體
/// /summary>
    public class Person
    {
        [MongoAlias("_id")]
        public string ID { get; set; }

        public string Name { get; set; }

        public int Age { get; set; }

        public DateTime CreateTime { get; set; }
    }
    #endregion

2:初始化一些變量

復(fù)制代碼 代碼如下:

string connectionString = string.Empty;

        string databaseName = string.Empty;

        string collectionName = string.Empty;

        static MongodbHelperT> mongodb;

        #region 初始化操作
/// summary>
/// 初始化操作
/// /summary>
        public MongodbHelper()
        {
            connectionString = "Server=127.0.0.1:2222";
            databaseName = "shopex";
            collectionName = "person";
        }
        #endregion

3:為了方便T的繼承類使用linq功能,我們還需要映射一下。

復(fù)制代碼 代碼如下:

#region 實(shí)現(xiàn)linq查詢的映射配置
        /// summary>
/// 實(shí)現(xiàn)linq查詢的映射配置
/// /summary>
        public MongoConfiguration configuration
        {
            get
            {
                var config = new MongoConfigurationBuilder();

                config.Mapping(mapping =>
                {
                    mapping.DefaultProfile(profile =>
                    {
                        profile.SubClassesAre(t => t.IsSubclassOf(typeof(T)));
                    });
                    mapping.MapT>();
                    mapping.MapT>();
                });

                config.ConnectionString(connectionString);

                return config.BuildConfiguration();
            }
        }
        #endregion

4:下面是一些基本的CURD的代碼,跟寫EF代碼很類似,寫起來好舒服。

復(fù)制代碼 代碼如下:

#region 插入操作
        /// summary>
/// 插入操作
/// /summary>
/// param name="person">/param>
/// returns>/returns>
        public void Insert(T t)
        {
            using (Mongo mongo = new Mongo(configuration))
            {
                try
                {
                    mongo.Connect();

                    var db = mongo.GetDatabase(databaseName);

                    var collection = db.GetCollectionT>(collectionName);

                    collection.Insert(t, true);

                    mongo.Disconnect();

                }
                catch (Exception)
                {
                    mongo.Disconnect();
                    throw;
                }
            }
        }
        #endregion

        #region 更新操作
        /// summary>
/// 更新操作
/// /summary>
/// param name="person">/param>
/// returns>/returns>
        public void Update(T t, ExpressionFuncT, bool>> func)
        {
            using (Mongo mongo = new Mongo(configuration))
            {
                try
                {
                    mongo.Connect();

                    var db = mongo.GetDatabase(databaseName);

                    var collection = db.GetCollectionT>(collectionName);

                    collection.UpdateT>(t, func, true);

                    mongo.Disconnect();

                }
                catch (Exception)
                {
                    mongo.Disconnect();
                    throw;
                }
            }
        }
        #endregion

        #region 獲取集合
        /// summary>
///獲取集合
/// /summary>
/// param name="person">/param>
/// returns>/returns>
        public ListT> List(int pageIndex, int pageSize, ExpressionFuncT, bool>> func, out int pageCount)
        {
            pageCount = 0;

            using (Mongo mongo = new Mongo(configuration))
            {
                try
                {
                    mongo.Connect();

                    var db = mongo.GetDatabase(databaseName);

                    var collection = db.GetCollectionT>(collectionName);

                    pageCount = Convert.ToInt32(collection.Count());

                    var personList = collection.Linq().Where(func).Skip(pageSize * (pageIndex - 1))
                                                   .Take(pageSize).Select(i => i).ToList();

                    mongo.Disconnect();

                    return personList;

                }
                catch (Exception)
                {
                    mongo.Disconnect();
                    throw;
                }
            }
        }
        #endregion

        #region 讀取單條記錄
        /// summary>
///讀取單條記錄
/// /summary>
/// param name="person">/param>
/// returns>/returns>
        public T Single(ExpressionFuncT, bool>> func)
        {
            using (Mongo mongo = new Mongo(configuration))
            {
                try
                {
                    mongo.Connect();

                    var db = mongo.GetDatabase(databaseName);

                    var collection = db.GetCollectionT>(collectionName);

                    var single = collection.Linq().FirstOrDefault(func);

                    mongo.Disconnect();

                    return single;

                }
                catch (Exception)
                {
                    mongo.Disconnect();
                    throw;
                }
            }
        }
        #endregion

        #region 刪除操作
        /// summary>
/// 刪除操作
/// /summary>
/// param name="person">/param>
/// returns>/returns>
        public void Delete(ExpressionFuncT, bool>> func)
        {
            using (Mongo mongo = new Mongo(configuration))
            {
                try
                {
                    mongo.Connect();

                    var db = mongo.GetDatabase(databaseName);

                    var collection = db.GetCollectionT>(collectionName);

                    //這個(gè)地方要注意,一定要加上T參數(shù),否則會(huì)當(dāng)作object類型處理
//導(dǎo)致刪除失敗
                    collection.RemoveT>(func);

                    mongo.Disconnect();

                }
                catch (Exception)
                {
                    mongo.Disconnect();
                    throw;
                }
            }
        }
        #endregion

5.   好,我們開一下2222端口,由于前前篇我已經(jīng)把這個(gè)mongodb做成了服務(wù),現(xiàn)在就直接連過去了,并做一下對Name的索引。

6. 一切準(zhǔn)備妥當(dāng),我們做下基本的操作,比如這里我添加一千條數(shù)據(jù),注意我開啟的是安全模式,如果插入不成功,將會(huì)拋出異常。

 1> Add:

 

復(fù)制代碼 代碼如下:

 static void Main(string[] args)
        {
            MongodbHelperPerson> helper = new MongodbHelperPerson>();

            //插入1000條數(shù)據(jù)
            for (int i = 0; i 1000; i++)
            {
                helper.Insert(new Person()
                {
                    ID = Guid.NewGuid().ToString(),
                    Name = "jack" + i,
                    Age = i,
                    CreateTime = DateTime.Now
                });
            }

            Console.WriteLine("插入成功");

            Console.Read();
        }
 


 乍一看顯示的數(shù)據(jù)以為有問題,為什么沒有出現(xiàn)jack0或者jack999,不過find的一下后心情舒坦了。

2> update:   這里就把jack941的名字改掉“mary”

復(fù)制代碼 代碼如下:

static void Main(string[] args)
        {
            MongodbHelperPerson> helper = new MongodbHelperPerson>();

            //修改jack941改成mary
            var single = helper.Single(i => i.Name == "jack941");
            single.Name = "mary";
            helper.Update(single, i => i.ID == single.ID);

            Console.WriteLine("修改成功");
            Console.Read();
        }

3>Delete:  刪除mary這條記錄

復(fù)制代碼 代碼如下:

static void Main(string[] args)
        {
            MongodbHelperPerson> helper = new MongodbHelperPerson>();

            //刪除mary這個(gè)記錄
            helper.Delete(i => i.Name == "mary");

            Console.WriteLine("刪除成功");
            Console.Read();
        }

4> list操作: 這里我獲取一下名字里面帶9的人數(shù)列表

復(fù)制代碼 代碼如下:

static void Main(string[] args)
        {
            MongodbHelperPerson> helper = new MongodbHelperPerson>();

            int pagecount;

            //獲取名字里面帶9的人數(shù)
            var list = helper.List(1, 20, i => i.Name.Contains("9"), out pagecount);

           Console.Read();
        }

總的運(yùn)行代碼

復(fù)制代碼 代碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Linq.Expressions;

using MongoDB.Configuration;
using MongoDB.Linq;
using MongoDB.Attributes;


namespace MongoDB.Test
{
    public class MongodbHelperT> where T : class
    {
        string connectionString = string.Empty;

        string databaseName = string.Empty;

        string collectionName = string.Empty;

        static MongodbHelperT> mongodb;

        #region 初始化操作
        /// summary>
/// 初始化操作
/// /summary>
        public MongodbHelper()
        {
            connectionString = "Server=127.0.0.1:2222";
            databaseName = "shopex";
            collectionName = "person";
        }
        #endregion

        #region 實(shí)現(xiàn)linq查詢的映射配置
        /// summary>
/// 實(shí)現(xiàn)linq查詢的映射配置
/// /summary>
        public MongoConfiguration configuration
        {
            get
            {
                var config = new MongoConfigurationBuilder();

                config.Mapping(mapping =>
                {
                    mapping.DefaultProfile(profile =>
                    {
                        profile.SubClassesAre(t => t.IsSubclassOf(typeof(T)));
                    });
                    mapping.MapT>();
                    mapping.MapT>();
                });

                config.ConnectionString(connectionString);

                return config.BuildConfiguration();
            }
        }
        #endregion

        #region 插入操作
        /// summary>
/// 插入操作
/// /summary>
/// param name="person">/param>
/// returns>/returns>
        public void Insert(T t)
        {
            using (Mongo mongo = new Mongo(configuration))
            {
                try
                {
                    mongo.Connect();

                    var db = mongo.GetDatabase(databaseName);

                    var collection = db.GetCollectionT>(collectionName);

                    collection.Insert(t, true);

                    mongo.Disconnect();

                }
                catch (Exception)
                {
                    mongo.Disconnect();
                    throw;
                }
            }
        }
        #endregion

        #region 更新操作
        /// summary>
/// 更新操作
/// /summary>
/// param name="person">/param>
/// returns>/returns>
        public void Update(T t, ExpressionFuncT, bool>> func)
        {
            using (Mongo mongo = new Mongo(configuration))
            {
                try
                {
                    mongo.Connect();

                    var db = mongo.GetDatabase(databaseName);

                    var collection = db.GetCollectionT>(collectionName);

                    collection.UpdateT>(t, func, true);

                    mongo.Disconnect();

                }
                catch (Exception)
                {
                    mongo.Disconnect();
                    throw;
                }
            }
        }
        #endregion

        #region 獲取集合
        /// summary>
///獲取集合
/// /summary>
/// param name="person">/param>
/// returns>/returns>
        public ListT> List(int pageIndex, int pageSize, ExpressionFuncT, bool>> func, out int pageCount)
        {
            pageCount = 0;

            using (Mongo mongo = new Mongo(configuration))
            {
                try
                {
                    mongo.Connect();

                    var db = mongo.GetDatabase(databaseName);

                    var collection = db.GetCollectionT>(collectionName);

                    pageCount = Convert.ToInt32(collection.Count());

                    var personList = collection.Linq().Where(func).Skip(pageSize * (pageIndex - 1))
                                                   .Take(pageSize).Select(i => i).ToList();

                    mongo.Disconnect();

                    return personList;

                }
                catch (Exception)
                {
                    mongo.Disconnect();
                    throw;
                }
            }
        }
        #endregion

        #region 讀取單條記錄
        /// summary>
///讀取單條記錄
/// /summary>
/// param name="person">/param>
/// returns>/returns>
        public T Single(ExpressionFuncT, bool>> func)
        {
            using (Mongo mongo = new Mongo(configuration))
            {
                try
                {
                    mongo.Connect();

                    var db = mongo.GetDatabase(databaseName);

                    var collection = db.GetCollectionT>(collectionName);

                    var single = collection.Linq().FirstOrDefault(func);

                    mongo.Disconnect();

                    return single;

                }
                catch (Exception)
                {
                    mongo.Disconnect();
                    throw;
                }
            }
        }
        #endregion

        #region 刪除操作
        /// summary>
/// 刪除操作
/// /summary>
/// param name="person">/param>
/// returns>/returns>
        public void Delete(ExpressionFuncT, bool>> func)
        {
            using (Mongo mongo = new Mongo(configuration))
            {
                try
                {
                    mongo.Connect();

                    var db = mongo.GetDatabase(databaseName);

                    var collection = db.GetCollectionT>(collectionName);

                    //這個(gè)地方要注意,一定要加上T參數(shù),否則會(huì)當(dāng)作object類型處理
//導(dǎo)致刪除失敗
                    collection.RemoveT>(func);

                    mongo.Disconnect();

                }
                catch (Exception)
                {
                    mongo.Disconnect();
                    throw;
                }
            }
        }
        #endregion
    }

    #region 數(shù)據(jù)實(shí)體
    /// summary>
/// 數(shù)據(jù)實(shí)體
/// /summary>
    public class Person
    {
        [MongoAlias("_id")]
        public string ID { get; set; }

        public string Name { get; set; }

        public int Age { get; set; }

        public DateTime CreateTime { get; set; }
    }
    #endregion
}

您可能感興趣的文章:
  • C#簡單操作MongoDB的步驟全紀(jì)錄
  • C#中如何將MongoDB->RunCommand結(jié)果映射到業(yè)務(wù)類的方法總結(jié)
  • Mongodb在CSharp里實(shí)現(xiàn)Aggregate實(shí)例
  • MongoDB實(shí)現(xiàn)基于關(guān)鍵詞的文章檢索功能(C#版)
  • C#中使用1.7版本驅(qū)動(dòng)操作MongoDB簡單例子
  • C# 對MongoDB 進(jìn)行增刪改查的簡單操作實(shí)例
  • 關(guān)于C#生成MongoDB中ObjectId的實(shí)現(xiàn)方法
  • C#基于Mongo的官方驅(qū)動(dòng)手?jǐn)]一個(gè)Super簡易版MongoDB-ORM框架

標(biāo)簽:本溪 丹東 吉安 邯鄲 景德鎮(zhèn) 昭通 鶴崗 大理

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《MongoDB入門教程之C#驅(qū)動(dòng)操作實(shí)例》,本文關(guān)鍵詞  MongoDB,入門教程,之,驅(qū)動(dòng),;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《MongoDB入門教程之C#驅(qū)動(dòng)操作實(shí)例》相關(guān)的同類信息!
  • 本頁收集關(guān)于MongoDB入門教程之C#驅(qū)動(dòng)操作實(shí)例的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章