欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

MongoDB入门教程之C#驱动操作实例

程序员文章站 2022-11-22 18:51:29
作为系列的最后一篇,得要说说c#驱动对mongodb的操作,目前驱动有两种:官方驱动和samus驱动,不过我个人还是喜欢后者, 因为提供了丰富的linq操作,相当方便。...

作为系列的最后一篇,得要说说c#驱动对mongodb的操作,目前驱动有两种:官方驱动和samus驱动,不过我个人还是喜欢后者,

因为提供了丰富的linq操作,相当方便。

官方驱动:。下载后,还提供了一个酷似msdn的帮助文档。

samus驱动:。

下面就具体看看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的索引。

MongoDB入门教程之C#驱动操作实例

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();
        }
 


MongoDB入门教程之C#驱动操作实例

 乍一看显示的数据以为有问题,为什么没有出现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();
        }

MongoDB入门教程之C#驱动操作实例

<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();
        }

MongoDB入门教程之C#驱动操作实例

<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();
        }

MongoDB入门教程之C#驱动操作实例

总的运行代码

复制代码 代码如下:

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
}