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
}

时间: 2024-11-06 03:38:21

MongoDB入门教程之C#驱动操作实例_MongoDB的相关文章

Zend Framework入门教程之Zend_Session会话操作详解

本文实例讲述了Zend Framework入门教程之Zend_Session会话操作.分享给大家供大家参考,具体如下: 会话命名空间 实现会话 代码: <?php require_once "Zend/Session/Namespace.php"; $myNamespace = new Zend_Session_Namespace('Myspace'); if(isset($myNamespace->numberOfPageRequests)) { $myNamespace

AngularJS入门教程之Cookies读写操作示例_AngularJS

本文实例讲述了AngularJS的Cookies读写操作.分享给大家供大家参考,具体如下: 虽然使用JavaScript创建和获取Cookie很简单,AngularJS还是把它作为一个单独的模块进行了封装,模块名为ngCookies,和前面的教程中做法一样,先引入angular-cookies.js: <script type="text/javascript" src="angular-1.3.0.14/angular-cookies.js"><

MongoDB入门教程之Windows下的MongoDB数据库安装图解_MongoDB

   关于mongodb的好处,优点之类的这里就不说了,唯一要讲的一点就是mongodb中有三元素:数据库,集合,文档,其中"集合" 就是对应关系数据库中的"表","文档"对应"行".  一: 下载       上MongoDB官网 ,我们发现有32bit和64bit,这个就要看你系统了,不过这里有两点注意:           ①:根据业界规则,偶数为"稳定版"(如:1.6.X,1.8.X),奇数为&qu

Zend Framework入门教程之Zend_Db数据库操作详解

本文实例讲述了Zend Framework中Zend_Db数据库操作方法.分享给大家供大家参考,具体如下: 引言:Zend操作数据库通过Zend_Db_Adapter 它可以连接多种数据库,可以是DB2数据库.MySQli数据库.Oracle数据库.等等. 只需要配置相应的参数就可以了. 下面通过案例来展示一下其连接数据库的过程. 连接mysql数据库 代码: <?php require_once 'Zend/Db.php'; $params = array('host'=>'127.0.0.

PHP入门教程之Web访问MySQL实例教程

mysql_connect()函数 定义和用法 mysql_connect() 函数打开非持久的 MySQL 连接. 语法 mysql_connect(server,user,pwd,newlink,clientflag) 例子  代码如下 复制代码 <?php $con = mysql_connect("localhost","mysql_user","mysql_pwd"); if (!$con)   {   die('Could no

php入门教程之Zend Studio设置与开发实例_php技巧

本文实例讲述了php入门教程之Zend Studio设置与开发方法.分享给大家供大家参考,具体如下: 新建文档的模板设置 新建文档的模板设置 Demo1.php: <?php echo "阅谁问君诵,水落清香浮." ?> orderform.php: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD

Zend Framework入门教程之Zend_Mail用法示例_php实例

本文实例讲述了Zend Framework入门教程之Zend_Mail用法.分享给大家供大家参考,具体如下: Zend_Mail组件提供了通用化的功能来创建和发送文本. Zend_Mail通过PHP内建的mail()函数或者直接通过SMTP连接来发送邮件. 一个简单的邮件由收件人.主题.邮件内容以及发件人等内容组成. 步骤如下 1.创建对象 2.设置邮件内容 3.发送 案例: <?php require_once "Zend/Mail.php"; $my_mail = new Z

Zend Framework入门教程之Zend_View组件用法示例

本文实例讲述了Zend Framework入门教程之Zend_View组件用法.分享给大家供大家参考,具体如下: Zend_View组件可以实现MVC模式中视图部分的代码与Model和Controller部分的分离. 使用步骤:首先在Controller中建立一个Zend_View实例,并将需要的变量传递给它:之后,Controller通知Zend_View显示一个特定的视图, 生成View输出的内容. 实例之控制器代码脚本: <?php //使用模型来获取书籍作者和标题相关数据 $data =

Zend Framework入门教程之Zend_Mail用法示例

本文实例讲述了Zend Framework入门教程之Zend_Mail用法.分享给大家供大家参考,具体如下: Zend_Mail组件提供了通用化的功能来创建和发送文本. Zend_Mail通过PHP内建的mail()函数或者直接通过SMTP连接来发送邮件. 一个简单的邮件由收件人.主题.邮件内容以及发件人等内容组成. 步骤如下 1.创建对象 2.设置邮件内容 3.发送 案例: <?php require_once "Zend/Mail.php"; $my_mail = new Z