初学MongoDB之C#驱动

来源:爱站网时间:2020-09-27编辑:网友分享
初学MongoDB的过程中,很多都是新的知识,只有深入了解后才知道它们怎么运用,下面小编就来给大家说说C#驱动中操作MongoDB数据的方法和代码示例,给有需要的朋友可以参考下。

初学MongoDB的过程中,很多都是新的知识,只有深入了解后才知道它们怎么运用,下面小编就来给大家说说C#驱动中操作MongoDB数据的方法和代码示例,给有需要的朋友可以参考下。

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

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

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

下面就具体看看samus驱动,上面提供了一个简单的demo,大体上看看我们就知道怎么玩了。

一: 实践

1:我们建立一个Person实体,MongoAlias特性表示取别名,这里的ID值将会覆盖掉数据库自动生成的_id。

复制代码 代码如下:

#region 数据实体
    ///
/// 数据实体
///

    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 mongodb;

        #region 初始化操作
///


/// 初始化操作
///

        public MongodbHelper()
        {
            connectionString = "Server=127.0.0.1:2222";
            databaseName = "shopex";
            collectionName = "person";
        }
        #endregion

 

3:为了方便T的继承类使用linq功能,我们还需要映射一下。

复制代码 代码如下:

#region 实现linq查询的映射配置
        ///
/// 实现linq查询的映射配置
///

        public MongoConfiguration configuration
        {
            get
            {
                var config = new MongoConfigurationBuilder();

 

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

                config.ConnectionString(connectionString);

                return config.BuildConfiguration();
            }
        }
        #endregion

 

4:下面是一些基本的CURD的代码,跟写EF代码很类似,写起来好舒服。

复制代码 代码如下:

#region 插入操作
        ///
/// 插入操作
///

///
///
        public void Insert(T t)
        {
            using (Mongo mongo = new Mongo(configuration))
            {
                try
                {
                    mongo.Connect();

 

                    var db = mongo.GetDatabase(databaseName);

                    var collection = db.GetCollection(collectionName);

                    collection.Insert(t, true);

                    mongo.Disconnect();

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

        #region 更新操作
        ///


/// 更新操作
///

///
///
        public void Update(T t, Expression> func)
        {
            using (Mongo mongo = new Mongo(configuration))
            {
                try
                {
                    mongo.Connect();

                    var db = mongo.GetDatabase(databaseName);

                    var collection = db.GetCollection(collectionName);

                    collection.Update(t, func, true);

                    mongo.Disconnect();

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

        #region 获取集合
        ///


///获取集合
///

///
///
        public List List(int pageIndex, int pageSize, Expression> func, out int pageCount)
        {
            pageCount = 0;

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

                    var db = mongo.GetDatabase(databaseName);

                    var collection = db.GetCollection(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 读取单条记录
        ///


///读取单条记录
///

///
///
        public T Single(Expression> func)
        {
            using (Mongo mongo = new Mongo(configuration))
            {
                try
                {
                    mongo.Connect();

                    var db = mongo.GetDatabase(databaseName);

                    var collection = db.GetCollection(collectionName);

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

                    mongo.Disconnect();

                    return single;

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

        #region 删除操作
        ///


/// 删除操作
///

///
///
        public void Delete(Expression> func)
        {
            using (Mongo mongo = new Mongo(configuration))
            {
                try
                {
                    mongo.Connect();

                    var db = mongo.GetDatabase(databaseName);

                    var collection = db.GetCollection(collectionName);

                    //这个地方要注意,一定要加上T参数,否则会当作object类型处理
//导致删除失败
                    collection.Remove(func);

                    mongo.Disconnect();

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

 

5.   好,我们开一下2222端口,由于前前篇我已经把这个mongodb做成了服务,现在就直接连过去了,并做一下对Name的索引。

6. 一切准备妥当,我们做下基本的操作,比如这里我添加一千条数据,注意我开启的是安全模式,如果插入不成功,将会抛出异常。

  Add:

复制代码 代码如下:

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

 

            //插入1000条数据
            for (int i = 0; i             {
                helper.Insert(new Person()
                {
                    ID = Guid.NewGuid().ToString(),
                    Name = "jack" + i,
                    Age = i,
                    CreateTime = DateTime.Now
                });
            }

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

            Console.Read();
        }
 

 

 

 乍一看显示的数据以为有问题,为什么没有出现jack0或者jack999,不过find的一下后心情舒坦了。

update:   这里就把jack941的名字改掉“mary”

复制代码 代码如下:

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

 

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

 

Delete:  删除mary这条记录

复制代码 代码如下:

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

 

            //删除mary这个记录
            helper.Delete(i => i.Name == "mary");

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

 

list操作: 这里我获取一下名字里面带9的人数列表

复制代码 代码如下:

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

 

            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 where T : class
    {
        string connectionString = string.Empty;

        string databaseName = string.Empty;

        string collectionName = string.Empty;

        static MongodbHelper mongodb;

        #region 初始化操作
        ///


/// 初始化操作
///

        public MongodbHelper()
        {
            connectionString = "Server=127.0.0.1:2222";
            databaseName = "shopex";
            collectionName = "person";
        }
        #endregion

        #region 实现linq查询的映射配置
        ///


/// 实现linq查询的映射配置
///

        public MongoConfiguration configuration
        {
            get
            {
                var config = new MongoConfigurationBuilder();

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

                config.ConnectionString(connectionString);

                return config.BuildConfiguration();
            }
        }
        #endregion

        #region 插入操作
        ///


/// 插入操作
///

///
///
        public void Insert(T t)
        {
            using (Mongo mongo = new Mongo(configuration))
            {
                try
                {
                    mongo.Connect();

                    var db = mongo.GetDatabase(databaseName);

                    var collection = db.GetCollection(collectionName);

                    collection.Insert(t, true);

                    mongo.Disconnect();

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

        #region 更新操作
        ///


/// 更新操作
///

///
///
        public void Update(T t, Expression> func)
        {
            using (Mongo mongo = new Mongo(configuration))
            {
                try
                {
                    mongo.Connect();

                    var db = mongo.GetDatabase(databaseName);

                    var collection = db.GetCollection(collectionName);

                    collection.Update(t, func, true);

                    mongo.Disconnect();

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

        #region 获取集合
        ///


///获取集合
///

///
///
        public List List(int pageIndex, int pageSize, Expression> func, out int pageCount)
        {
            pageCount = 0;

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

                    var db = mongo.GetDatabase(databaseName);

                    var collection = db.GetCollection(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 读取单条记录
        ///


///读取单条记录
///

///
///
        public T Single(Expression> func)
        {
            using (Mongo mongo = new Mongo(configuration))
            {
                try
                {
                    mongo.Connect();

                    var db = mongo.GetDatabase(databaseName);

                    var collection = db.GetCollection(collectionName);

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

                    mongo.Disconnect();

                    return single;

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

        #region 删除操作
        ///


/// 删除操作
///

///
///
        public void Delete(Expression> func)
        {
            using (Mongo mongo = new Mongo(configuration))
            {
                try
                {
                    mongo.Connect();

                    var db = mongo.GetDatabase(databaseName);

                    var collection = db.GetCollection(collectionName);

                    //这个地方要注意,一定要加上T参数,否则会当作object类型处理
//导致删除失败
                    collection.Remove(func);

                    mongo.Disconnect();

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

    #region 数据实体
    ///


/// 数据实体
///

    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的教程,感兴趣的朋友不妨关注下。

上一篇:初学MongoDB之主从复制配置

下一篇:MongoDB实现数据分页和排序案例

您可能感兴趣的文章

相关阅读

热门软件源码

最新软件源码下载