博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#操作mongodb数据库
阅读量:7001 次
发布时间:2019-06-27

本文共 5807 字,大约阅读时间需要 19 分钟。

1、下载驱动:

如下图:选择c#解决方案,右键,点击 “管理NuGet程序包(N)...”

在弹出的对话框中,输入MongoDB.Driver,进行搜索,然后选择安装。

2、引用命名空间:

using MongoDB.Bson;

using MongoDB.Driver;
using MongoDB.Driver.Core;

3、程序代码

 

配置文件:

 

 

public class iCTRMongodbCache : CacheBase
{
  IMongoCollection<BsonDocument> _collect;
  IMongoDatabase _db;
  string _collectionName = "";
  /// <summary>
  /// 默认搜索列字段名称
  /// </summary>
  string defaultColumn = ConfigurationManager.AppSettings["DefaultColumn"].ToString();

  /// <summary>

  /// 构造函数
  /// </summary>
  /// <param name="collectionName">集合名称,类似关系型数据库中的表名</param>
  public iCTRMongodbCache(string collectionName)
    : base(collectionName)
  {
    _collectionName = collectionName;
    string mongoDB_Host = ConfigurationManager.AppSettings["MongoDB_Host"].ToString();
    string mongoDB_DbName = ConfigurationManager.AppSettings["MongoDB_DbName"].ToString();
    string mongoDB_UserName = ConfigurationManager.AppSettings["MongoDB_UserName"].ToString();
    string mongoDB_Password = ConfigurationManager.AppSettings["MongoDB_Password"].ToString();
    MongoDB.Driver.MongoClient mc = new MongoClient(mongoDB_Host);

    _db = mc.GetDatabase(mongoDB_DbName);

    _collect = _db.GetCollection<BsonDocument>(collectionName);
  }

  public override bool Append(string keyValue, string value)
  {
    if (string.IsNullOrEmpty(value) || value.IndexOf(":") < 0)
     {
      return false;
     }
    Dictionary<string, string> dictR = new Dictionary<string, string>();
    dictR.Add(defaultColumn, keyValue);
    try
    {
      string[] values = value.Split(',');
      foreach (string keyv in values)
      {
        dictR.Add(keyv.Split(':')[0], keyv.Split(':')[1]);
      }
      BsonDocument bd = new BsonDocument();
      bd.AddRange(dictR);
      _collect.InsertOne(bd);
    }
    catch (System.InvalidOperationException ex)
    {
      throw ex;
    }
    return true;
  }

  public override object Get(string keyValue)

  {
    Dictionary<string,object> dict =new Dictionary<string,object>();
    dict.Add(defaultColumn, keyValue);
    var query = new BsonDocument(dict);
    IAsyncCursor<BsonDocument> result = _collect.FindSync(query);
    List<BsonDocument> list = null;
    if (result.MoveNext())
    {
      list = result.Current as List<BsonDocument>;
    }
    return list;
  }
  public override T Get<T>(string keyValue)
  {
    Dictionary<string, object> dict = new Dictionary<string, object>();
    dict.Add(defaultColumn, keyValue);
    var query = new BsonDocument(dict);
    IAsyncCursor<BsonDocument> result = _collect.FindSync(query);
    if (result.MoveNext())
    {
      List<BsonDocument> list = result.Current as List<BsonDocument>;
      if (list != null)
      {
        BsonDocument bd = list[0];
        bd.Remove("_id");
        bd.Remove(defaultColumn);
        JavaScriptSerializer Serializer = new JavaScriptSerializer();
        Serializer.MaxJsonLength = int.MaxValue;
        return Serializer.Deserialize<T>(bd.ToString());
      }
      else
      {
        return default(T);
      }
    }
    else
    {
      return default(T);
    }
  }

  public override void Set(string keyValue, object value, DateTime expiration)

  {
    Dictionary<string, object> dictR = new Dictionary<string, object>();
    dictR.Add(defaultColumn, keyValue);
    try
      {
        BsonDocument bd = value.ToBsonDocument();
        bd.AddRange(dictR);
        _collect.InsertOne(bd);
      }
    catch (System.InvalidOperationException ex)
      {
        throw ex;
      }

    }

 

  public override void Set<T>(string keyValue, T value)

  {
    Dictionary<string, object> dictR = new Dictionary<string, object>();
    dictR.Add(defaultColumn, keyValue);
    try
      {
        BsonDocument bd = value.ToBsonDocument<T>();
        bd.AddRange(dictR);
        _collect.InsertOne(bd);
      }
    catch (System.InvalidOperationException ex)
    {
      throw ex;
    }
  }
  public override void Remove(string key)
  {
    Dictionary<string, object> dictR = new Dictionary<string, object>();
    dictR.Add(defaultColumn, key);
    _collect.DeleteOne(new BsonDocument(dictR));

  }

  public override void Clear()

  {
    _db.DropCollection(_collectionName);
  }

  public override void Dispose()

  {
    _db.DropCollection(_collectionName);
    _collect = null;
  }
 }

 

4、测试代码

using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MongodbCache.Caching;
namespace UnitTest
{
  [TestClass]
  public class iCTRMongodbCacheTest
  {
    private iCTRMongodbCache _cache;
    public iCTRMongodbCacheTest()
    {
    _cache = new iCTRMongodbCache("test1");
  }

  [TestMethod]

  public void TestAppend()
  {
    //ID454为主键字段对应的数据,"age:43,name:Marry为要插入的数据,
    //调用缓存的Append方法,第二个参数必须为类似"column1 : column1Value,column2 : column2Value "的数据
    _cache.Append("ID1", "age:43,name:Marry");
  }

  [TestMethod]

  public void TestSet1()
  {
    Dictionary<string, string> dict = new Dictionary<string, string>();
    dict.Add("age", "12");
    dict.Add("Name", "Marry");
    _cache.Set("ID2", dict);
  }
  [TestMethod]
  public void TestSet2()
  {
    student s = new student();
    s.age = 234;
    s.name = "lengli";
    _cache.Set<student>("ID3", s);
  }

  [TestMethod]

  public void TestRemove()
  {
    string ID = "ID1";
    _cache.Remove(ID);
  }

  [TestMethod]

  public void TestGet1()
  {
    object obj = _cache.Get("ID2");
  }

  [TestMethod]
  public void TestGet2()
  {
    student dd = _cache.Get<student>("ID3");
  }

  [TestMethod]

  public void TestClear()
  {
    _cache.Clear();
  }

  [TestClass]

  class student
  {
    public string name
    {
      get;
      set;
    }

    public int age
    {
      get;
      set;
    }

  }

  }
}

转载于:https://www.cnblogs.com/shaosks/p/5754051.html

你可能感兴趣的文章
解决 UE4 无法找到。generated.h 办法
查看>>
python 读取SQLServer数据插入到MongoDB数据库中
查看>>
TCP的三次握手与四次挥手(详解+动图)
查看>>
装饰器
查看>>
shell基础(八)-循环语句
查看>>
python3.6 安装jupyter,打不开notebook
查看>>
【转】loadrunner场景对性能测试策略的映射
查看>>
JMeter性能测试,完整入门篇
查看>>
[转]怪异的CheckedListBox数据绑定
查看>>
.Net的异步机制(委托Delegate) - STEP 1
查看>>
Django配合使用Jquery post方法
查看>>
hadoop再次集群搭建(3)-如何选择相应的hadoop版本
查看>>
spring mvc default-servlet mvc:resources mvc:default-servlet-handler区别
查看>>
ORACLE存储过程 练习系列一 关键字 部门树
查看>>
理解 Visual C++ 应用程序的依赖项(msdn)
查看>>
HTML初步学习9
查看>>
Dubbo&Zookeeper运行原理
查看>>
viewstate加密(转)
查看>>
nginx 设置websocket支持
查看>>
数字逻辑之逻辑符号、逻辑电路图、真值表
查看>>