程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> MongoDB數據庫 >> MongoDB綜合知識 >> MongoDB入門教程之C#驅動操作實例

MongoDB入門教程之C#驅動操作實例

編輯:MongoDB綜合知識

作為系列的最後一篇,得要說說C#驅動對mongodb的操作,目前驅動有兩種:官方驅動和samus驅動,不過我個人還是喜歡後者,

因為提供了豐富的linq操作,相當方便。

官方驅動:https://github.com/mongodb/mongo-csharp-driver/downloads。下載後,還提供了一個酷似msdn的幫助文檔。

samus驅動:https://github.com/samus/mongodb-csharp/downloads。

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

一個簡單的demo,大體上看看我們就知道怎麼玩了。

一: 實踐

1:我們建立一個Person實體,MongoAlias特性表示取別名,這裡的ID值將會覆蓋掉數據庫自動生成的_id。
復制代碼 代碼如下:
#region 數據實體
    /// <summary>
/// 數據實體
/// </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:初始化一些變量

復制代碼 代碼如下:
string connectionString = string.Empty;

        string databaseName = string.Empty;

        string collectionName = string.Empty;

        static MongodbHelper<T> mongodb;

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

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

復制代碼 代碼如下:
#region 實現linq查詢的映射配置
        /// <summary>
/// 實現linq查詢的映射配置
/// </summary>
        public MongoConfiguration configuration
        {
            get
            {
                var config = new MongoConfigurationBuilder();

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

                config.ConnectionString(connectionString);

                return config.BuildConfiguration();
            }
        }
        #endregion

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

復制代碼 代碼如下:
#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.GetCollection<T>(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, Expression<Func<T, bool>> func)
        {
            using (Mongo mongo = new Mongo(configuration))
            {
                try
                {
                    mongo.Connect();

                    var db = mongo.GetDatabase(databaseName);

                    var collection = db.GetCollection<T>(collectionName);

                    collection.Update<T>(t, func, true);

                    mongo.Disconnect();

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

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

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

                    var db = mongo.GetDatabase(databaseName);

                    var collection = db.GetCollection<T>(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(Expression<Func<T, bool>> func)
        {
            using (Mongo mongo = new Mongo(configuration))
            {
                try
                {
                    mongo.Connect();

                    var db = mongo.GetDatabase(databaseName);

                    var collection = db.GetCollection<T>(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(Expression<Func<T, bool>> func)
        {
            using (Mongo mongo = new Mongo(configuration))
            {
                try
                {
                    mongo.Connect();

                    var db = mongo.GetDatabase(databaseName);

                    var collection = db.GetCollection<T>(collectionName);

                    //這個地方要注意,一定要加上T參數,否則會當作object類型處理
//導致刪除失敗
                    collection.Remove<T>(func);

                    mongo.Disconnect();

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

5.   好,我們開一下2222端口,由於前前篇我已經把這個mongodb做成了服務,現在就直接連過去了,並做一下對Name的索引。

6. 一切准備妥當,我們做下基本的操作,比如這裡我添加一千條數據,注意我開啟的是安全模式,如果插入不成功,將會拋出異常。

 <1> Add:

 復制代碼 代碼如下:
 static void Main(string[] args)
        {
            MongodbHelper<Person> helper = new MongodbHelper<Person>();

            //插入1000條數據
            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();
        }
 

 乍一看顯示的數據以為有問題,為什麼沒有出現jack0或者jack999,不過find的一下後心情舒坦了。

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

復制代碼 代碼如下:
static void Main(string[] args)
        {
            MongodbHelper<Person> helper = new MongodbHelper<Person>();

            //修改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這條記錄

復制代碼 代碼如下:
static void Main(string[] args)
        {
            MongodbHelper<Person> helper = new MongodbHelper<Person>();

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

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

<4> list操作: 這裡我獲取一下名字裡面帶9的人數列表

復制代碼 代碼如下:
static void Main(string[] args)
        {
            MongodbHelper<Person> helper = new MongodbHelper<Person>();

            int pagecount;

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

           Console.Read();
        }

總的運行代碼

復制代碼 代碼如下:
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 MongodbHelper<T> where T : class
    {
        string connectionString = string.Empty;

        string databaseName = string.Empty;

        string collectionName = string.Empty;

        static MongodbHelper<T> mongodb;

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

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

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

                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.GetCollection<T>(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, Expression<Func<T, bool>> func)
        {
            using (Mongo mongo = new Mongo(configuration))
            {
                try
                {
                    mongo.Connect();

                    var db = mongo.GetDatabase(databaseName);

                    var collection = db.GetCollection<T>(collectionName);

                    collection.Update<T>(t, func, true);

                    mongo.Disconnect();

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

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

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

                    var db = mongo.GetDatabase(databaseName);

                    var collection = db.GetCollection<T>(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(Expression<Func<T, bool>> func)
        {
            using (Mongo mongo = new Mongo(configuration))
            {
                try
                {
                    mongo.Connect();

                    var db = mongo.GetDatabase(databaseName);

                    var collection = db.GetCollection<T>(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(Expression<Func<T, bool>> func)
        {
            using (Mongo mongo = new Mongo(configuration))
            {
                try
                {
                    mongo.Connect();

                    var db = mongo.GetDatabase(databaseName);

                    var collection = db.GetCollection<T>(collectionName);

                    //這個地方要注意,一定要加上T參數,否則會當作object類型處理
//導致刪除失敗
                    collection.Remove<T>(func);

                    mongo.Disconnect();

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

    #region 數據實體
    /// <summary>
/// 數據實體
/// </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
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved