QQ登录

只需要一步,快速开始

APP扫码登录

只需要一步,快速开始

查看: 4927|回复: 0

[C#/.NET] MongoDB C# Driver 快速入门

[复制链接]

等级头衔

积分成就    金币 : 2861
   泡泡 : 1516
   精华 : 6
   在线时间 : 1328 小时
   最后登录 : 2026-7-17

丰功伟绩

优秀达人突出贡献荣誉管理论坛元老活跃会员

联系方式
发表于 2021-7-30 08:22:55 来自手机 | 显示全部楼层 |阅读模式
      MongoDB的官方C#驱动可以通过这个链接得到。链接提供了.msi和.zip两种方式获取驱动dll文件。C#驱动的基本数据库连接,增删改查操作。在使用C#驱动的时候,要在工程中添加"MongoDB.Bson.dll"和"MongoDB.Driver.dll"的引用。同时要在代码中加入下面两个using语句。) U/ q( R! {! Q( M* f1 Z
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
using System.Text;

2 A: y' j. g  r8 |* Y! K1 g0 ]注册常用约定, I! O- o2 r- |( i, h
  public static void RigisterConventions()
        {
            var pack = new ConventionPack();
            //元素名称序列化成驼峰形式
            pack.Add(new CamelCaseElementNameConvention());
            ConventionRegistry.Register("MyConventions", pack, x => true);
        }

7 U# z, _. N, S$ g0 Y& Q! p, Z初始化Mongo帮助类
) M6 t* ]: g1 L- `  v, T8 i3 j
  /// <summary>
        /// 初始化Mongo帮助类
        /// </summary>
        /// <param name="connectionString">连接字符串</param>
        /// <param name="dbName">数据库名</param>
        public MongoHelper(string connectionString, string dbName)
        {
            _client = new MongoClient(connectionString);
            _database = _client.GetDatabase(dbName);
        }
( J" p* W/ U; F" W; [4 H
获取集合: Q" W5 ]3 _7 K7 E$ U# N1 f
   /// <summary>
        /// 获取集合
        /// </summary>
        /// <typeparam name="T">集合类型</typeparam>
        /// <param name="collectionName">集合名</param>
        /// <returns></returns>
        public IMongoCollection<T> GetCollection<T>(string collectionName)
        {
            return _database.GetCollection<T>(collectionName);
        }
) l4 H& _) @$ _8 b5 {% S1 \' N
完整代码4 ^) H* m+ {* V% t' ^
/// <summary>
    /// MongoDB访问帮助类
    /// </summary>
    public class MongoHelper
    {
        private MongoClient _client;
        private IMongoDatabase _database;

        /// <summary>
        ///  注册常用约定
        /// </summary>
        public static void RigisterConventions()
        {
            var pack = new ConventionPack();
            //元素名称序列化成驼峰形式
            pack.Add(new CamelCaseElementNameConvention());
            ConventionRegistry.Register("MyConventions", pack, x => true);
        }

        /// <summary>
        /// 初始化Mongo帮助类
        /// </summary>
        /// <param name="connectionString">连接字符串</param>
        /// <param name="dbName">数据库名</param>
        public MongoHelper(string connectionString, string dbName)
        {
            _client = new MongoClient(connectionString);
            _database = _client.GetDatabase(dbName);
        }

        /// <summary>
        /// 数据库
        /// </summary>
        public IMongoDatabase Db => _database;

        /// <summary>
        /// 获取集合
        /// </summary>
        /// <typeparam name="T">集合类型</typeparam>
        /// <param name="collectionName">集合名</param>
        /// <returns></returns>
        public IMongoCollection<T> GetCollection<T>(string collectionName)
        {
            return _database.GetCollection<T>(collectionName);
        }

        /// <summary>
        /// 获取Queryable对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="collectionName">集合名</param>
        /// <returns></returns>
        public IMongoQueryable<T> GetQueryable<T>(string collectionName)
        {
            return GetCollection<T>(collectionName).AsQueryable();
        }

        /// <summary>
        /// 模糊查询转换特殊字符:正则表达式有以下特殊字符。需要转义  * . ? + $ ^ [ ] ( ) { } | \ /
        /// 如:{"phone":/U9G\/XoDNo8ozbwbxal\+Qzg==/}
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ChangeSpecialCharacter(string str)
        {
            if (string.IsNullOrEmpty(str))
                return str;
            StringBuilder retValue = new StringBuilder();
            string str1 = "*.?+$^[](){}|\\/";
            for (int i = 0; i < str.Length; i++)
            {
                string ss = str[i].ToString();
                if (str1.Contains(ss))
                {
                    ss = "\" + ss;
                }
                retValue.Append(ss);
            }
            return retValue.ToString();
        }

4 j% Y, G& d9 Y& Z# \& O" y% i, h5 P
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|小黑屋|paopaomj.COM ( 渝ICP备18007172号|渝公网安备50010502503914号 )

GMT+8, 2026-8-5 06:45

Powered by paopaomj X3.5 © 2016-2025 sitemap

快速回复 返回顶部 返回列表