栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

Mongodb c#增删改查

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Mongodb c#增删改查

写在前面

最近项目需要,就研究了下mongodb,也是为了快速上手,就自己弄了一个简单的例子,这里记录一下。

Mongodb

传统的关系数据库一般由数据库(database)、表(table)、记录(record)三个层次概念组成,MongoDB是由数据库(database)、集合(collection)、文档对象(document)三个层次组成。MongoDB对于关系型数据库里的表,但是集合中没有列、行和关系概念,这体现了模式自由的特点。

那么在c#如何使用呢?下面看个例子,你会发现上手非常简单。

要操作数据库,首先考虑的就是连接字符串的问题,因为这就相当于你从那儿拿数据,先要有路子才行。

MongoDB 标准连接字符串

mongodb://[username:password@]host1[:port1][,host2[:port2],…[,hostN[:portN]]][/[database][?options]]

mongodb:// 是连接字串必须的前缀字串。

username:password@ 可选项,连接到数据库后会尝试验证登陆。

host1 必须的指定至少一个host。

:portX 可选项,默认连接到27017

/database 如果指定username:password@,连接并验证登陆指定数据库。若不指定,默认打开admin数据库。

?options 是连接选项。如果不使用/database,则前面需要加上/。所有连接选项都是键值对name=value,键值对之间通过&或;(分号)隔开。

关于options可参考官网的东西。

说这些不如先上个例子,先上手实践一下。

1          /// 
2         /// 连接字符串
3         /// 
4         private static readonly string _connectionString = "mongodb://sa:sa@192.168.1.105:27017/Test_mongo";
5         private static readonly string _dbName = "Test_mongo";

在c#中使用Mongodb需要引入如下的dll
采用Nuget进行安装就可以了。

增删改查的代码如下:

 1        ///  
 2         /// 新增 
 3         ///  
 4         ///  
 5         private static void Insert(Customer customer)
 6         { 
 7             //创建mogodb对象 
 8             using (Mongo mongo = new Mongo(_connectionString)) 
 9             {
 10                 //连接mongodb
 11                 mongo.Connect();
 12                 //获得要操作的数据库
 13                 var db = mongo.GetDatabase(_dbName);
 14                 //获取要操作的Collection
 15                 var collection = db.GetCollection();
 16                 collection.Insert(customer);              
 17             }
 18         }
 19         /// 
 20         /// 批量添加
 21         /// 
 22         /// 
 23         private static void InsertList(List lstCustomer)
 24         {
 25             using (Mongo mongo = new Mongo(_connectionString))
 26             {
 27                 mongo.Connect();
 28                 var db = mongo.GetDatabase(_dbName);
 29                 var collection = db.GetCollection();
 30                 collection.Insert(lstCustomer);
 31             }
 32         }
 33         /// 
 34         /// 更新
 35         /// 
 36         /// 
 37         private static void Update(Customer customer)
 38         {
 39             using (Mongo mongo = new Mongo(_connectionString))
 40             {
 41                 mongo.Connect();
 42                 var db = mongo.GetDatabase(_dbName);
 43                 var collection = db.GetCollection();
 44                 //更新对象
 45                 collection.Update(customer, (x => x.CustomerID == customer.CustomerID));
 46             }
 47         }
 48         /// 
 49         /// 获取所有的customer
 50         /// 
 51         /// 
 52         private static IList GetList()
 53         {
 54             using (Mongo mongo = new Mongo(_connectionString))
 55             {
 56                 mongo.Connect();
 57                 var db = mongo.GetDatabase(_dbName);
 58                 var collection = db.GetCollection();
 59                 ICursor mogoCollection = collection.FindAll();
 60               
 61                 return mogoCollection.documents.ToList();
 62             }
 63         }
 64         /// 
 65         /// 根据id获取单个对象
 66         /// 
 67         /// 
 68         /// 
 69         private static Customer GetById(string customerId)
 70         {
 71             using (Mongo mongo = new Mongo(_connectionString))
 72             {
 73                 mongo.Connect();
 74                 var db = mongo.GetDatabase(_dbName);
 75                 var collection = db.GetCollection();
 76                 return collection.FindOne(x => x.CustomerID == customerId);
 77             }
 78         }
 79     }
 80     [Serializable]
 81     class Customer
 82     {
 83         [MongoId]
 84         public string CustomerID { set; get; }
 85         public string CustomerName { set; get; }
 86         public string ContactName { set; get; }
 87         public string Address { set; get; }
 88         public string PostalCode { set; get; }
 89         public string Tel { set; get; }
 90     }

测试

 1 static void Main(string[] args) 
 2         { 
 3             #region 批量插入 
 4             //List list = new List(); 
 5             //for (int i = 0; i < 100; i++) 
 6             //{ 
 7             //    Customer customer = new Customer() 
 8             //    { 
 9             //        CustomerID = Guid.NewGuid().ToString(),
 10             //        Address = "北京" + i.ToString(),
 11             //        CustomerName = "wolfy" + i.ToString(),
 12             //        Tel = "123" + i.ToString(),
 13             //        PostalCode = "221212" + i.ToString(),
 14             //        ContactName = "wolfy" + i.ToString()
 15             //    };
 16             //    list.Add(customer);
 17             //}
 18             //InsertList(list); 
 19             #endregion
 20             #region 更新
 21             //更新需要先将该对象查询出,然后更新修改的值,不然其他的值为null
 22             //Update(new Customer() { CustomerID = "08dca525-fb6d-4984-a55f-53723a6ce39c", ContactName = "wolfy22222" });
 23             #endregion
 24             #region 查询单个对象和集合
 25             //Customer customer = GetById("8211501b-4341-4acb-b2fa-d6a714765443");
 26             //Console.WriteLine(new JavascriptSerializer().Serialize(customer));
 27             List customers = GetList().ToList();
 28             Console.WriteLine(new JavascriptSerializer().Serialize(customers));
 29             #endregion
 30             Console.Read();
 31         }

总结    

到这里就结束了,这里弄了一个简单例子,算是快速上手的例子。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/231239.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号