• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

MongoDB学习笔记(四)C#操作MongoDB

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

C#驱动对mongodb的操作,目前驱动有两种:官方驱动和samus驱动,不过我个人还是喜欢后者,

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

 

官方驱动:https://github.com/mongodb/mongo-csharp-driver/downloads。下载后,还提供了一个酷似msdn的帮助文档。

samus驱动:https://github.com/samus/mongodb-csharp/downloads。 

封装的 MongoDBHepler

 public class MongoDBHepler<T> where T:class
    {
//数据库连接字符串区分大小写 public static string connectionString =ConfigurationManager.AppSettings["mongodbconn"].ToString(); public static string databaseName = ConfigurationManager.AppSettings["mongodbName"].ToString(); #region 初始化操作 /// <summary> /// /// </summary> /// <param name="strdatabaseName"></param> /// <param name="strcollectionName"></param> public MongoDBHepler() { } #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> /// <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>(); collection.Insert(t, true); mongo.Disconnect(); } catch (Exception) { mongo.Disconnect(); throw; } } } public void Insert(List<T> list) { using (Mongo mongo = new Mongo(configuration)) { try { mongo.Connect(); var db = mongo.GetDatabase(databaseName); var collection = db.GetCollection<T>(); collection.Insert(list, true); mongo.Disconnect(); } catch (Exception) { mongo.Disconnect(); throw; } } } #endregion #region 更新操作 /// <summary> /// 更新操作 /// </summary> /// <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>(); collection.Update<T>(t, func, true); mongo.Disconnect(); } catch (Exception) { mongo.Disconnect(); throw; } } } #endregion #region 获取集合 /// <summary> ///获取集合 /// </summary> /// <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>(); 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; } } } public List<T> List(Expression<Func<T, bool>> func) { using (Mongo mongo = new Mongo(configuration)) { try { mongo.Connect(); var db = mongo.GetDatabase(databaseName); var collection = db.GetCollection<T>(); var personList = collection.Linq().Where(func).Select(i => i).ToList(); mongo.Disconnect(); return personList; } catch (Exception) { mongo.Disconnect(); throw; } } } #endregion #region 读取单条记录 /// <summary> ///读取单条记录 /// </summary> /// <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>(); var single = collection.Linq().FirstOrDefault(func); mongo.Disconnect(); return single; } catch (Exception) { mongo.Disconnect(); throw; } } } #endregion #region 删除操作 /// <summary> /// 删除操作 /// </summary> /// <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>(); //这个地方要注意,一定要加上T参数,否则会当作object类型处理 //导致删除失败 collection.Remove<T>(func); mongo.Disconnect(); } catch (Exception) { mongo.Disconnect(); throw; } } } #endregion }

 

使用:

一: 实践

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

 1 #region 数据实体
2 /// <summary>
3 /// 数据实体
4 /// </summary>
5 public class Person
6 {
7 [MongoAlias("_id")]
8 public string ID { get; set; }
9
10 public string Name { get; set; }
11
12 public int Age { get; set; }
13
14 public DateTime CreateTime { get; set; }
15 }
16 #endregion

 

<1> Add:

 1    static void Main(string[] args)
2 {
3 MongodbHelper<Person> helper = new MongodbHelper<Person>();
4
5 //插入1000条数据
6 for (int i = 0; i < 1000; i++)
7 {
8 helper.Insert(new Person()
9 {
10 ID = Guid.NewGuid().ToString(),
11 Name = "jack" + i,
12 Age = i,
13 CreateTime = DateTime.Now
14 });
15 }
16
17 Console.WriteLine("插入成功");
18
19 Console.Read();
20 }

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

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

 1  static void Main(string[] args)
2 {
3 MongodbHelper<Person> helper = new MongodbHelper<Person>();
4
5 //修改jack941改成mary
6 var single = helper.Single(i => i.Name == "jack941");
7 single.Name = "mary";
8 helper.Update(single, i => i.ID == single.ID);
9
10 Console.WriteLine("修改成功");
11 Console.Read();
12 }

 

<3>Delete:  删除mary这条记录

 1      static void Main(string[] args)
2 {
3 MongodbHelper<Person> helper = new MongodbHelper<Person>();
4
5 //删除mary这个记录
6 helper.Delete(i => i.Name == "mary");
7
8 Console.WriteLine("删除成功");
9 Console.Read();
10 }


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

 1    static void Main(string[] args)
2 {
3 MongodbHelper<Person> helper = new MongodbHelper<Person>();
4
5 int pagecount;
6
7 //获取名字里面带9的人数
8 var list = helper.List(1, 20, i => i.Name.Contains("9"), out pagecount);
9
10 Console.Read();
11 }

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#面试题整理发布时间:2022-07-10
下一篇:
CSharpGL(19)用glReadPixels把渲染的内容保存为PNG图片(C#)发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap