MongoDB-Getting Started with the C# Driver
简介:本文仅提供快速入门级别的使用C# Driver操作MongoDB,高手跳过
- Downloading the C# Driver
- 添加相关的dll引用
MongoDB.Bson.dll MongoDB.Driver.dll
- 添加名称空间引用
using MongoDB.Bson; using MongoDB.Driver;
- 获取客户端对象
var connectionString = "mongodb://localhost"; var client = new MongoClient(connectionString);
- 获取服务端对象
var server = client.GetServer();
- 获取要操作的数据库
var database = server.GetDatabase("test"); // "test" is the name of the database
- CRUD(使用自定义的类)
- 自定义实体
public class Entity { public ObjectId Id { get; set; } public string Name { get; set; } }
- 获取要操作的表
// "entities" is the name of the collection var collection = database.GetCollection<Entity>("entities");
- 新增一条记录
var entity = new Entity { Name = "Tom" }; collection.Insert(entity); var id = entity.Id; // Insert will set the Id if necessary (as it was in this example)
- 查询一条记录
var query = Query<Entity>.EQ(e => e.Id, id); var entity = collection.FindOne(query);
- 保存一条记录(发送整个实体到数据库)
entity.Name = "Dick"; collection.Save(entity);
- 修改一条记录(仅发送修改的部分到数据库,这一点是和保存还是有区别的,根据场景来自行判断需要用哪一种来更新数据)
var query = Query<Entity>.EQ(e => e.Id, id); var update = Update<Entity>.Set(e => e.Name, "Harry"); // update modifiers collection.Update(query, update);
- 删除一条记录
var query = Query<Entity>.EQ(e => e.Id, id); collection.Remove(query);
- 自定义实体
完整演示代码:
1 using MongoDB.Bson; 2 using MongoDB.Driver; 3 using MongoDB.Driver.Builders; 4 using System; 5 using System.Collections.Generic; 6 using System.Linq; 7 using System.Linq.Expressions; 8 using System.Text; 9 using System.Threading.Tasks; 10 11 namespace MongoDBTest 12 { 13 class Program 14 { 15 static void Main(string[] args) 16 { 17 var connectionString = "mongodb://localhost:27017"; 18 var client = new MongoClient(connectionString); 19 var server = client.GetServer(); 20 var database = server.GetDatabase("test"); 21 var collection = database.GetCollection<Entity>("entities"); 22 var entity = new Entity { Name = "Tom" }; 23 var i = collection.Insert(entity); 24 var id = entity.Id; 25 26 var query = Query<Entity>.EQ(e => e.Id, id); 27 entity = collection.FindOne(query); 28 entity.Name = "Dick"; 29 var s = collection.Save(entity); 30 31 var update = Update<Entity>.Set(e => e.Name, "Harry"); 32 collection.Update(query, update); 33 34 35 collection.Remove(query); 36 37 Console.ReadKey(); 38 39 } 40 41 42 } 43 public class Entity 44 { 45 public ObjectId Id; 46 public string Name { get; set; } 47 } 48 49 }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。