c#驱动操作mongodb辅助类MongoDBHelper

using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;

/*
https://docs.mongodb.com/manual/tutorial/update-documents/
https://docs.mongodb.com/manual/tutorial/perform-two-phase-commits/
https://docs.mongodb.com/manual/reference/command/dropDatabase/index.html
https://docs.mongodb.com/manual/reference/command/listCommands/
*/

namespace MongoDbHelper
{
    public class MongoDBHelper
    {
        private string databaseName = string.Empty;
        private IMongoClient client = null;
        private IMongoDatabase database = null;

        public MongoDBHelper(string connectionString)
        {
            client = new MongoClient(connectionString);
        }

        public MongoDBHelper(string connectionString, string databaseName)
        {
            client = new MongoClient(connectionString);
            database = client.GetDatabase(databaseName);
        }

        public string DatabaseName
        {
            get { return databaseName; }
            set
            {
                databaseName = value;
                database = client.GetDatabase(databaseName);
            }
        }

        /// <summary>
        /// 执行命令,命令请参考MongoCommand,命令太多,不一一展示,传入的就是里面的字符串,有些命令执行需要连接到admin表
        /// </summary>
        /// <param name="cmdText"></param>
        /// <returns></returns>
        public BsonDocument RunCommand(string cmdText)
        {
            return database.RunCommand<BsonDocument>(cmdText);
        }

        public IList<BsonDocument> GetDatabase()
        {
            return client.ListDatabases().ToList();
        }

        #region SELECT
        /// <summary>
        /// 判断文档存在状态
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="documentname"></param>
        /// <param name="filterexist"></param>
        /// <returns></returns>
        public bool IsExistDocument<T>(string documentname, FilterDefinition<T> filter)
        {
            return database.GetCollection<T>(documentname).Count(filter) > 0;
        }

        /// <summary>
        /// 通过条件得到查询的结果个数
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="documentname"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public long GetCount<T>(string documentname, FilterDefinition<T> filter)
        {
            return database.GetCollection<T>(documentname).Count(filter);
        }

        /// <summary>
        /// 通过系统id(ObjectId)获取一个对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="documentname"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public T GetDocumentById<T>(string documentname, string id)
        {
            ObjectId oid = ObjectId.Parse(id);
            var filter = Builders<T>.Filter.Eq("_id", oid);
            var result = database.GetCollection<T>(documentname).Find(filter);
            return result.FirstOrDefault();
        }

        /// <summary>
        /// 通过系统id(ObjectId)获取一个对象同时过滤字段
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="documentname"></param>
        /// <param name="id"></param>
        /// <param name="fields"></param>
        /// <returns></returns>
        public T GetDocumentById<T>(string documentname, string id, ProjectionDefinition<T> fields)
        {
            ObjectId oid = ObjectId.Parse(id);
            var filter = Builders<T>.Filter.Eq("_id", oid);
            return database.GetCollection<T>(documentname).Find(filter).Project<T>(fields).FirstOrDefault();
        }

        /// <summary>
        /// 通过指定的条件获取一个对象,如果有多条,只取第一条,同时过滤字段
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="documentname"></param>
        /// <param name="filter"></param>
        /// <param name="fields"></param>
        /// <returns></returns>
        public T GetDocumentByUserFilter<T>(string documentname, FilterDefinition<T> filter, ProjectionDefinition<T> fields)
        {
            return database.GetCollection<T>(documentname).Find(filter).Project<T>(fields).FirstOrDefault();
        }

        /// <summary>
        /// 获取全部文档
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="documentname"></param>
        /// <returns></returns>
        public IList<T> GetAllDocuments<T>(string documentname)
        {
            var filter = Builders<T>.Filter.Empty;
            return database.GetCollection<T>(documentname).Find(filter).ToList();
        }

        /// <summary>
        /// 获取全部文档同时过滤字段
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="documentname"></param>
        /// <param name="fields">要获取的字段</param>
        /// <returns></returns>
        public IList<T> GetAllDocuments<T>(string documentname, ProjectionDefinition<T> fields)
        {
            var filter = Builders<T>.Filter.Empty;
            return database.GetCollection<T>(documentname).Find(filter).Project<T>(fields).ToList();
        }

        /// <summary>
        /// 通过一个条件获取对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="documentname"></param>
        /// <param name="property">字段名</param>
        /// <param name="value">字段值</param>
        /// <returns></returns>
        public IList<T> GetDocumentsByFilter<T>(string documentname, string property, string value)
        {
            FilterDefinition<T> filter = Builders<T>.Filter.Eq(property, value);
            return database.GetCollection<T>(documentname).Find(filter).ToList();
        }

        /// <summary>
        /// 通过条件获取对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="documentname"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public IList<T> GetDocumentsByFilter<T>(string documentname, FilterDefinition<T> filter)
        {
            return database.GetCollection<T>(documentname).Find(filter).ToList();
        }

        /// <summary>
        /// 通过条件获取对象,同时过滤字段
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="documentname"></param>
        /// <param name="property">字段名</param>
        /// <param name="value">字段值</param>
        /// <param name="fields">要获取的字段</param>
        /// <returns></returns>
        public IList<T> GetDocumentsByFilter<T>(string documentname, string property, string value, ProjectionDefinition<T> fields)
        {
            FilterDefinition<T> filter = Builders<T>.Filter.Eq(property, value);
            return database.GetCollection<T>(documentname).Find(filter).Project<T>(fields).ToList();
        }

        /// <summary>
        /// 通过条件获取对象,同时过滤数据和字段
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="documentname"></param>
        /// <param name="filter">过滤器</param>
        /// <param name="fields">要获取的字段</param>
        /// <returns></returns>
        public IList<T> GetDocumentsByFilter<T>(string documentname, FilterDefinition<T> filter, ProjectionDefinition<T> fields)
        {
            return database.GetCollection<T>(documentname).Find(filter).Project<T>(fields).ToList();
        }

        /// <summary>
        /// 通过条件获取分页的文档并排序
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="documentname"></param>
        /// <param name="filter"></param>
        /// <param name="sort"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public IList<T> GetPagedDocumentsByFilter<T>(string documentname, FilterDefinition<T> filter, ProjectionDefinition<T> fields, SortDefinition<T> sort, int pageIndex, int pageSize)
        {
            IList<T> result = new List<T>();
            if (pageIndex != 0 && pageSize != 0)
            {
                result = database.GetCollection<T>(documentname).Find(filter).Project<T>(fields).Sort(sort).Skip(pageSize * (pageIndex - 1)).Limit(pageSize).ToList();
            }
            else
            {
                result = database.GetCollection<T>(documentname).Find(filter).Project<T>(fields).Sort(sort).ToList();
            }
            return result;
        }

        /// <summary>
        /// 通过条件获取分页的文档并排序
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="documentname"></param>
        /// <param name="filter"></param>
        /// <param name="sort"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public IList<T> GetPagedDocumentsByFilter<T>(string documentname, FilterDefinition<T> filter, SortDefinition<T> sort, int pageIndex, int pageSize)
        {
            IList<T> result = new List<T>();
            if (pageIndex != 0 && pageSize != 0)
            {
                result = database.GetCollection<T>(documentname).Find(filter).Sort(sort).Skip(pageSize * (pageIndex - 1)).Limit(pageSize).ToList();
            }
            else
            {
                result = database.GetCollection<T>(documentname).Find(filter).Sort(sort).ToList();
            }
            return result;
        }

        /// <summary>
        /// 通过条件获取分页的文档
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="documentname"></param>
        /// <param name="filter"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public IList<T> GetPagedDocumentsByFilter<T>(string documentname, FilterDefinition<T> filter, int pageIndex, int pageSize)
        {
            IList<T> result = new List<T>();
            if (pageIndex != 0 && pageSize != 0)
            {
                result = database.GetCollection<T>(documentname).Find(filter).Skip(pageSize * (pageIndex - 1)).Limit(pageSize).ToList();
            }
            else
            {
                result = database.GetCollection<T>(documentname).Find(filter).ToList();
            }
            return result;
        }

        /// <summary>
        /// 获取分页的文档
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="documentname"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public IList<T> GetPagedDocumentsByFilter<T>(string documentname, SortDefinition<T> sort, int pageIndex, int pageSize)
        {
            IList<T> result = new List<T>();
            var filter = Builders<T>.Filter.Empty;
            if (pageIndex != 0 && pageSize != 0)
            {
                result = database.GetCollection<T>(documentname).Find(filter).Sort(sort).Skip(pageSize * (pageIndex - 1)).Limit(pageSize).ToList();
            }
            else
            {
                result = database.GetCollection<T>(documentname).Find(filter).Sort(sort).ToList();
            }
            return result;
        }

        /// <summary>
        /// 获取分页的文档
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="documentname"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public IList<T> GetPagedDocumentsByFilter<T>(string documentname, int pageIndex, int pageSize)
        {
            IList<T> result = new List<T>();
            var filter = Builders<T>.Filter.Empty;
            if (pageIndex != 0 && pageSize != 0)
            {
                result = database.GetCollection<T>(documentname).Find(filter).Skip(pageSize * (pageIndex - 1)).Limit(pageSize).ToList();
            }
            else
            {
                result = database.GetCollection<T>(documentname).Find(filter).ToList();
            }
            return result;
        }
        #endregion

        #region INSERT

        /// <summary>
        /// 新增
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="document"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public void Insert<T>(string documentName, T document)
        {
            try
            {
                database.GetCollection<T>(documentName).InsertOne(document);
            }
            catch (MongoWriteException me)
            {
                MongoBulkWriteException mbe = me.InnerException as MongoBulkWriteException;
                if (mbe != null && mbe.HResult == -2146233088)
                    throw new Exception("插入重复的键!");
                throw new Exception(mbe.Message);
            }
            catch (Exception ep)
            {
                throw ep;
            }
        }

        /// <summary>
        /// 新增多个文档
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="documentname"></param>
        /// <param name="documents"></param>
        /// <returns></returns>
        public void InsertMany<T>(string documentname, IList<T> documents)
        {
            try
            {
                database.GetCollection<T>(documentname).InsertMany(documents);
            }
            catch (MongoWriteException me)
            {
                MongoBulkWriteException mbe = me.InnerException as MongoBulkWriteException;
                if (mbe != null && mbe.HResult == -2146233088)
                    throw new Exception("插入重复的键!");
                throw new Exception(mbe.Message);
            }
            catch (Exception ep)
            {
                throw ep;
            }
        }
        #endregion

        #region UPDATE
        /// <summary>
        /// 修改
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="documentname"></param>
        /// <param name="filterexist"></param>
        /// <param name="id"></param>
        /// <param name="oldinfo"></param>
        /// <returns></returns>
        public void UpdateReplaceOne<T>(string documentname, string id, T oldinfo)
        {
            ObjectId oid = ObjectId.Parse(id);
            var filter = Builders<T>.Filter.Eq("_id", oid);
            database.GetCollection<T>(documentname).ReplaceOne(filter, oldinfo);
        }

        /// <summary>
        /// 只能替换一条,如果有多条的话
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="documentname"></param>
        /// <param name="filter"></param>
        /// <param name="oldinfo"></param>
        public void UpdateReplaceOne<T>(string documentname, FilterDefinition<T> filter, T oldinfo)
        {
            database.GetCollection<T>(documentname).ReplaceOne(filter, oldinfo);
        }

        /// <summary>
        /// 更新指定属性值,按ID就只有一条,替换一条
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="documentname"></param>
        /// <param name="id"></param>
        /// <param name="setvalue"></param>
        /// <returns></returns>
        public void Update<T>(string documentname, string id, string property, string value)
        {
            ObjectId oid = ObjectId.Parse(id);
            var filter = Builders<T>.Filter.Eq("_id", oid);
            var update = Builders<T>.Update.Set(property, value);
            database.GetCollection<T>(documentname).UpdateOne(filter, update);
        }

        public void Update<T>(string documentname, FilterDefinition<T> filter, UpdateDefinition<T> update)
        {
            database.GetCollection<T>(documentname).UpdateOne(filter, update);
        }

        public void UpdateMany<T>(string documentname, FilterDefinition<T> filter, UpdateDefinition<T> update)
        {
            database.GetCollection<T>(documentname).UpdateMany(filter, update);
        }

        #endregion

        #region DELETE
        /// <summary>
        /// 删除一个文档
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="documentname"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public void Delete<T>(string documentname, string id)
        {
            ObjectId oid = ObjectId.Parse(id);
            var filterid = Builders<T>.Filter.Eq("_id", oid);
            database.GetCollection<T>(documentname).DeleteOne(filterid);
        }

        public void Delete<T>(string documentname, string property, string value)
        {
            FilterDefinition<T> filter = Builders<T>.Filter.Eq(property, value);
            database.GetCollection<T>(documentname).DeleteOne(filter);
        }

        /// <summary>
        /// 通过一个属性名和属性值删除多个文档
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="documentname"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public void DeleteMany<T>(string documentname, string property, string value)
        {
            FilterDefinition<T> filter = Builders<T>.Filter.Eq(property, value);
            database.GetCollection<T>(documentname).DeleteMany(filter);
        }

        /// <summary>
        /// 通过一个属性名和属性值删除多个文档
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="documentname"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public void DeleteMany<T>(string documentname, FilterDefinition<T> filter)
        {
            database.GetCollection<T>(documentname).DeleteMany(filter);
        }
        #endregion

        /// <summary>
        /// 有些命令要求你连到系统库上才能执行
        /// You need to link to the admin table if you want to run system command;eg:listDatabases ,the following url show you the details
        /// https://docs.mongodb.com/manual/reference/command/listCommands/
        /// </summary>
        public sealed class MongoCommand
        {
            public const string ListDatabases = "{listDatabases:1}";
            public const string ListCommands = "{ listCommands: 1 }";
        }
    }
}

原文地址:https://www.cnblogs.com/jiangqw/p/12132315.html

时间: 2024-10-29 11:29:58

c#驱动操作mongodb辅助类MongoDBHelper的相关文章

MongoDB学习比较-07 C#驱动操作MongoDB

下载驱动 驱动的下载有两种方式:一种是在C#项目中通过NuGet进行安装,另一种是通过下面的链接:https://github.com/mongodb/mongo-csharp-driver/releases 直接下载msi进行安装或zip压缩包.不管哪种方式,其主要的目的都是获取两个dll文件:MongoDB.Bson.dll.MongoDB.Driver.dll.这是在程序中需要引用的两个类库文件. .NET版本要求 目前最新版的C#驱动是1.9.2,是在 .NET3.5的基础上构建的,所以

在C#中使用官方驱动操作MongoDB

MongoDB的官方驱动下载地址:https://github.com/mongodb/mongo-csharp-driver/releases 目前最新的版本是2.10,支持.NET 4.5以上.由于我现在的程序还在.NET4.0上面构建,所以这里使用1.10.1版本. 添加引用 解压下载到的驱动,然后在我们的程序中添加引用: MongoDB.Bson.dll MongoDB.Driver.dll 然后在代码中添加Using: using MongoDB.Bson; using MongoDB

[转]MongoDB学习 C#驱动操作MongoDB

下载驱动 驱动的下载有两种方式:一种是在C#项目中通过NuGet进行安装,另一种是通过下面的链接:https://github.com/mongodb/mongo-csharp-driver/releases 直接下载msi进行安装或zip压缩包.不管哪种方式,其主要的目的都是获取两个dll文件:MongoDB.Bson.dll.MongoDB.Driver.dll.这是在程序中需要引用的两个类库文件. .NET版本要求 目前最新版的C#驱动是1.9.2,是在 .NET3.5的基础上构建的,所以

学习MongoDB--(11):应用举例(利用java操作MongoDB)

原文地址:http://blog.csdn.net/drifterj/article/details/7948090 目录地址:http://blog.csdn.net/DrifterJ/article/category/1191327/2 前面我们都是通过shell来操作存取MongoDB的数据,shell中使用的语言就是javascript.我们这次说一下如何通过Java来访问操作MongoDB数据库的. Java驱动程序是MongoDB最早的驱动,已用于生产环境很长时间,十分稳定.可以到M

MongoDB基础入门003--使用官方驱动操作mongo,C#

本篇先简单介绍一下,使用官方驱动来操作MongoDB.至于MongoDB原生的增删改查语句,且等以后再慢慢学习. 一.操作MongoDB的驱动主要有两个 1.官方驱动:https://github.com/mongodb/mongo-csharp-driver/downloads,更新的还是比较及时的,目前已经支持大部门linq语法. 2.samus驱动:https://github.com/samus/mongodb-csharp/downloads. 这个好像很久都没有更新了,估计是被抛弃了

Ruby2.3.3操作MongoDB入门(Mongo驱动版本2.4.3)-先期准备&数据库连接创建

最近在学习MongoDB的相应知识,涉及到使用Ruby操作MongoDB数据库,因为参考数据中使用的Ruby Mongo驱动版本不是2.3.3,所以在操作方面会有所不同,因此撰写了这篇Ruby2.3.3操作MongoDB入门,学习方式是参考网址https://docs.mongodb.com/ruby-driver/v2.3/quick-start/ 快速学习主要分为以下几个部分: 先期准备 1.1 本地启动MongoDB数据库,端口号27017 Windows环境下启动方式如下:首先CMD命令

Ruby操作MongoDB(进阶)-CRUD操作

MongDB数据库的使用离不开CRUD操作.什么是CRUD,就是创建文档,读取文档信息,更新文档和删除文档. key-value键值对标记 在MongoDB的Ruby驱动中,Key_value键值多次出现.而且有时会出现语法上的巧合,这取决于在使用的Ruby版本中如何申明. 在文档创建步骤中,1.9及之后版本支持以下语法: document={name:"Tom",age:20}. 但是如果你使用的是2.2或者更高的版本,你可以用双引号将你的key包起来.如: document={&q

Java操作MongoDB

先引入mongo-java-dirver驱动 <!-- mongo-java-dirver --> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.4.2</version> </dependency> 代码操作演示: package com.simpl

C# 操作mongodb 分组

c#操作mongodb的分组的简单例子: 1.首先要下载c#对应的mongodb驱动,官方下载地址:https://github.com/mongodb/mongo-csharp-driver/releases,目前版本是2.3.0 然后引用相应的命名空间, using MongoDB.Bson; using MongoDB.Driver; using MongoDB.Driver.Core; 2.实例代码: /// <summary> /// 数据集合,类似关系型数据库中的表 /// <