MongoDB-Getting Started with the C# Driver

简介:本文仅提供快速入门级别的使用C# Driver操作MongoDB,高手跳过

  1. Downloading the C# Driver
    1. 猛击下载
  2. 添加相关的dll引用
        MongoDB.Bson.dll
    MongoDB.Driver.dll
  3. 添加名称空间引用
    using MongoDB.Bson;
    using MongoDB.Driver;
  4. 获取客户端对象
    var connectionString = "mongodb://localhost";
    var client = new MongoClient(connectionString);
  5. 获取服务端对象
    var server = client.GetServer();
  6. 获取要操作的数据库
    var database = server.GetDatabase("test"); // "test" is the name of the database
  7. CRUD(使用自定义的类)
    1. 自定义实体
      public class Entity
      {
      public ObjectId Id { get; set; } public string Name { get; set; }
      }
    2. 获取要操作的表
      // "entities" is the name of the collection
      var collection = database.GetCollection<Entity>("entities");
    3. 新增一条记录
      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)
    4. 查询一条记录
      var query = Query<Entity>.EQ(e => e.Id, id);
      var entity = collection.FindOne(query);
    5. 保存一条记录(发送整个实体到数据库)
      entity.Name = "Dick";
      collection.Save(entity);
    6. 修改一条记录(仅发送修改的部分到数据库,这一点是和保存还是有区别的,根据场景来自行判断需要用哪一种来更新数据)
      var query = Query<Entity>.EQ(e => e.Id, id);
      var update = Update<Entity>.Set(e => e.Name, "Harry"); // update modifiers
      collection.Update(query, update);
    7. 删除一条记录
      var query = Query<Entity>.EQ(e => e.Id, id);
      collection.Remove(query);

完整演示代码:

 using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks; namespace MongoDBTest
{
class Program
{
static void Main(string[] args)
{
var connectionString = "mongodb://localhost:27017";
var client = new MongoClient(connectionString);
var server = client.GetServer();
var database = server.GetDatabase("test");
var collection = database.GetCollection<Entity>("entities");
var entity = new Entity { Name = "Tom" };
var i = collection.Insert(entity);
var id = entity.Id; var query = Query<Entity>.EQ(e => e.Id, id);
entity = collection.FindOne(query);
entity.Name = "Dick";
var s = collection.Save(entity); var update = Update<Entity>.Set(e => e.Name, "Harry");
collection.Update(query, update); collection.Remove(query); Console.ReadKey(); } }
public class Entity
{
public ObjectId Id;
public string Name { get; set; }
} }
上一篇:echarts图表标签(axisLabel)折行


下一篇:JavaScript 应用开发 #2:视图与模板