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

Posted 一品码农

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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。 这个好像很久都没有更新了,估计是被抛弃了吧。(ps:据说之前使用起来很是nb啊)

驱动的下载:一种方法是,直接使用上面的连接下载。使用vs开发的同学都懂,我们强大的vs有个软件包管理工具(nuget),使用起来非常舒服。现在就介绍如何使用nuget,来安装MongoDB的驱动程序吧。

打开nuget,输入mongo,安装上MongoDB.Driver,mongocsharpdriver即可。请看下图:

二、增删改查操作。

1.新增

static void Main(string[] args)
        {
            string connectionString = "mongodb://localhost:27017";

            var client = new MongoClient(connectionString);
            var database = client.GetDatabase("local");
            var collection = database.GetCollection<person>("person");

            //批量插入1000条数据
            for (int i = 0; i < 1000; i++)
            {
                person p = new person();
                p.age = i % 10 + 1;
                p.createTime = DateTime.Now;
                p.name = "rj" + i;

                collection.InsertOne(p);
            }

            Console.ReadKey();
        }
新增1000条数据

2.查询

 //根据条件取出一条
            var find1 = collection.Find(item => item.name == "rj0").FirstOrDefault();
            //取出指定页数
            var find2 = collection.AsQueryable().Skip(10).Take(10).ToList();
查询

3.修改(ps:Builders<T>是很强大的)

 //修改
            var query = Builders<person>.Filter.Where(item => item.name == "rj0");

            var set = Builders<person>.Update.Set(item => item.name, "abc");

            collection.FindOneAndUpdate<person>(query, set);
View Code

4.删除

collection.FindOneAndDelete(item => item.name == "abc");
View Code

 

三、基本的增删改查已经演示,下面上传一份整理的MongoDBHelper类。

using MongoDB.Driver;
using MongoDB.Driver.Builders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using MongoDB.Driver.Linq;
using MongoDB.Bson;
using System.Configuration;

namespace MyMongoDB2
{
    public class MongoDBHelper
    {
        private static readonly string connectionString = "mongodb://admin:admin@localhost";// ConfigurationManager.AppSettings["mongodbServerList"];

        MongoClientSettings setting = null;
        MongoServer server = null;

        private string databaseName = "test";// string.Empty;

        private string tableName = "person";//string.Empty;

        #region 构造函数重载
        /// <summary>
        /// 默认开启
        /// </summary>
        public MongoDBHelper() : this(true) { }

        /// <summary>
        /// 默认副本级,指定连接串可实现单个mongodb
        /// </summary>
        public MongoDBHelper(bool replica) : this(replica, connectionString) { }

        /// <summary>
        /// 默认副本级,指定连接串可实现单个mongodb
        /// </summary>
        public MongoDBHelper(bool replica, string conn) : this(replica, conn, string.Empty, string.Empty) { }


        public MongoDBHelper(bool replica, string conn, string databasename)
                             : this(replica, conn, databasename, string.Empty)
        { }

        public MongoDBHelper(string databasename, string tablename)
                     : this(true, connectionString, databasename, tablename)
        { }

        public MongoDBHelper(string databasename)
             : this(databasename, string.Empty)
        { }

        public MongoDBHelper(bool replica, string conn, string databasename, string tablename)
        {
            //副本集
            if (replica)
            {
                var ips = conn.Split(\';\');

                var servicesList = new List<MongoServerAddress>();

                foreach (var ip in ips)
                {
                    var host = ip.Split(\':\')[0];
                    var port = Convert.ToInt32(ip.Split(\':\')[1]);

                    servicesList.Add(new MongoServerAddress(host, port));
                }

                setting = new MongoClientSettings()
                {
                    ReplicaSetName = "datamip",
                    Servers = servicesList
                };

                server = new MongoClient(setting).GetServer();
            }
            else
            {
                //普通的mongodb实例
                server = new MongoClient(conn).GetServer();
            }

            this.databaseName = databasename;
            this.tableName = tablename;
        }
        #endregion



        #region 删除操作 

        public bool Remove<T>(Expression<Func<T, bool>> func) => Remove<T>(databaseName, tableName, func);

        public bool Remove<T>(string table, Expression<Func<T, bool>> func) => Remove<T>(databaseName, table, func);

        public bool Remove<T>(string database, string table, Expression<Func<T, bool>> func)
        {
            try
            {
                var db = server.GetDatabase(database);

                var collection = db.GetCollection<T>(table);

                var query = Query<T>.Where(func);

                var result = collection.Remove(query);

                return Convert.ToInt32(Convert.ToDouble(result.Response["ok"].RawValue)) > 0;
            }
            catch (Exception ex)
            {
                //LogHelper.WriteLog(string.Format("Remove 失败: {0} ", ex.Message), ex);
                return false;
            }
        }


        public bool RemoveAll<T>() => RemoveAll<T>(databaseName, tableName);

        public bool RemoveAll<T>(string table) => RemoveAll<T>(databaseName, table);

        public bool RemoveAll<T>(string database, string table)
        {
            try
            {
                var db = server.GetDatabase(database);

                var collection = db.GetCollection<T>(table);

                var result = collection.RemoveAll();

                return Convert.ToInt32(Convert.ToDouble(result.Response["ok"].RawValue)) > 0;
            }
            catch (Exception ex)
            {
                //LogHelper.WriteLog(string.Format("Remove 失败: {0} ", ex.Message), ex);
                return false;
            }
        }

        #endregion



        #region 插入操作
        public bool Insert<T>(T t) => Insert<T>(databaseName, tableName, t);

        public bool Insert<T>(string table, T t) => Insert<T>(databaseName, table, t);

        public bool Insert<T>(string database, string table, T t)
        {
            try
            {
                var db = server.GetDatabase(database);   //mongodb中的数据库

                var collection = db.GetCollection<T>(table);

                var result = collection.Insert(t);

                return Convert.ToInt32(Convert.ToDouble(result.Response["ok"].RawValue)) > 0;
            }
            catch (Exception ex)
            {
                //LogHelper.WriteLog(string.Format("Insert 失败: {0} ", ex.Message), ex);
                return false;
            }
        }
        #endregion


        #region Save操作 【存在就更新,不存在就插入】
        public bool Save<T>(T t) => Save<T>(databaseName, tableName, t);

        public bool Save<T>(string table, T t) => Save<T>(databaseName, table, t);

        public bool Save<T>(string database, string table, T t)
        {
            try
            {
                var db = server.GetDatabase(database);   //mongodb中的数据库

                var collection = db.GetCollection<T>(table);

                var result = collection.Save(t);

                return Convert.ToInt32(Convert.ToDouble(result.Response["ok"].RawValue)) > 0;
            }
            catch (Exception ex)
            {
                //LogHelper.WriteLog(string.Format("Save 失败: {0} ", ex.Message), ex);
                return false;
            }
        }
        #endregion


        #region 批量插入

        public bool InsertBulk<T>(IEnumerable<T> list) => InsertBulk(tableName, list);

        public bool InsertBulk<T>(string table, IEnumerable<T> list) => InsertBulk<T>(databaseName, table, list);

        public bool InsertBulk<T>(string database, string table, IEnumerable<T> list)
        {
            try
            {
                //如果不判断count,mongodb会抛出异常,所以这里加上一个判断
                if (list == null || list.Count() == 0) return true;

                var db = server.GetDatabase(database);   //mongodb中的数据库

                var collection = db.GetCollection<T>(table);

                collection.InsertBatch(list);

                return true;
            }
            catch (Exception ex)
            {
                //LogHelper.WriteLog(string.Format("InsertBulk 失败: {0} ", ex.Message), ex);

                return false;
            }
        }


        #endregion


        #region 查找操作

        public List<T> Find<T>(Expression<Func<T, bool>> func) => Find<T>(tableName, func);

        public List<T> Find<T>(string table, Expression<Func<T, bool>> func) => Find<T>(databaseName, table, func);

        public List<T> Find<T>(string database, string table, Expression<Func<T, bool>> func)
        {
            var list = new List<T>();

            try
            {
                var db = server.GetDatabase(database);    //mongodb中的数据库

                var collection = db.GetCollection<T>(table);

                list = collection.Find(Query<T>.Where(func)).ToList();
            }
            catch (Exception ex)
            {
                //LogHelper.WriteLog(string.Format("Find 失败: {0} ", ex.Message), ex);

                throw;
            }

            return list;
        }


        public T FindOne<T>(Expression<Func<T, bool>> func) => FindOne<T>(tableName, func);

        public T FindOne<T>(string table, Expression<Func<T, bool>> func) => FindOne<T>(databaseName, table, func);

        public T FindOne<T>(string database, string table, Expression<Func<T, bool>> func)
        {
            var t = default(T);

            try
            {
                var db = server.GetDatabase(database);    //mongodb中的数据库

                var collection = db.GetCollection<T>(table);

                t = collection.FindOne(Query<T>.Where(func));
            }
            catch (Exception ex)
            {
                //LogHelper.WriteLog(string.Format("FindOne 失败: {0} ", ex.Message), ex);

                throw;
            }

            return t;
        }

        #endregion


        #region 查找并删除 【只能查找找匹配的第一条】,找到就删除

        public T FindOneAndRemove<T>(Expression<Func<T, bool>> func)
             => FindOneAndRemove(databaseName, tableName, func);

        public T FindOneAndRemove<T>(string table, Expression<Func<T, bool>> func)
                    => FindOneAndRemove(databaseName, table, func);

        public T FindOneAndRemove<T>(string database, string table, Expression<Func<T, bool>> func)
        {
            T t = default(T);

            try
            {
                var db = server.GetDatabase(database);   //mongodb中的数据库

                var collection = db.GetCollection<T>(table);

                FindAndRemoveArgs args = new FindAndRemoveArgs();

                args.Query = Query<T>.Where(func);

                var findAndModifyResult = collection.FindAndRemove(args);

                t = findAndModifyResult.GetModifiedDocumentAs<T>();
            }
            catch (Exception ex)
            {
                //LogHelper.WriteLog(string.Format("SearchAndRemove 失败: {0} ", ex.Message), ex);
            }

            return t;
        }

        #endregion



        #region  目前支持修改一个参数,找到并修改

        public T FindOneAndModify<T, A>(Expression<Func<T, bool>> func, Expression<Func<T, A>> arg1key, A arg1value)
                                     => FindOneAndModify(databaseName, tableName, func, arg1key, arg1value);

        public T FindOneAndModify<T, A>(string table, Expression<Func<T, bool>> func, Expression<Func<T, A>> arg1key, A arg1value)
                                             => FindOneAndModify(databaseName, table, func, arg1key, arg1value);

        public T FindOneAndModify<T, A>(string database, string table, Expression<Func<T, bool>> func, Expression<Func<T, A>> arg1key, A arg1value)
        {
            T t = default(T);

            try
            {
                var db = server.GetDatabase(database);   //mongodb中的数据库

                var collection = db.GetCollection<T>(table);

                FindAndModifyArgs args = new FindAndModifyArgs();

                args.Query = Query<T>.Where(func);

                args.Update = Update<T>.Set<A>(arg1key, arg1value);

                var findAndModifyResult = collection.FindAndModify(args);

                t = findAndModifyResult.GetModifiedDocumentAs<T>();
            }
            catch (Exception ex)
            {
                //LogHelper.WriteLog(string.Format("SearchOneAndModify 失败: {0} ", ex.Message), ex);
            }

            return t;
        }
        #endregion


        #region 更新记录

        /// <summary>
        /// 已指定“批量更新”
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="A"></typeparam>
        /// <param name="func"></param>
        /// <param name="arg1key"></param>
        /// <param name="arg1value"></param>
        /// <returns></returns>
        public bool Modify<T, A>(Expression<Func<T, bool>> func, Expression<Func<T, A>> arg1key, A arg1value)
                            => Modify<T, A>(databaseName, tableName, func, arg1key, arg1value);

        /// <summary>
        /// 已指定“批量更新”
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="A"></typeparam>
        /// <param name="table"></param>
        /// <param name="func"></param>
        /// <param name="arg1key"></param>
        /// <param name="arg1value"></param>
        /// <returns></returns>
        public bool Modify<T, A>(string table, Expression<Func<T, bool>> func, Expression<Func<T, A>> arg1key, A arg1value)
            => Modify<T, A>(databaseName, table, func, arg1key, arg1value);

        /// <summary>
        /// 已指定“批量更新”
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="A"></typeparam>
        /// <param name="database"></param>
        /// <param name="table"></param>
        /// <param name="func"></param>
        /// <param name="arg1key"></param>
        /// <param name="arg1value"></param>
        /// <returns></returns>
        public bool Modify<T, A>(string database, string table, Expression<Func<T, bool>> func, Expression<Func<T, A>> arg1key, A arg1value)
        {
            try
            {
                var db = server.GetDatabase(database);    //mongodb中的数据库

                var collection = db.GetCollection<T>(table);

                var query = Query<T>.Where(func);

                var update = Update<T>.Set(arg1key, arg1value);

                var writeConcernResult = collection.Update(query, update, UpdateFlags.Multi);

                return writeConcernResult.DocumentsAffected > 0;
            }
            catch (Exception ex)
            {
                //LogHelper.WriteLog(string.Format("Exists 失败: {0} ", ex.Message), ex);

                throw;
            }
        }

        #endregion



        #region 查询所有数据

        public List<T> FindAll<T>() => FindAll<T>(databaseName, tableName);

        public List<T> FindAll<T>(string table) => FindAll<T>(databaseName, table);

        public List<T> FindAll<T>(string database, string table)
        {
            var list = new List<T>();

            try
            {
                var db = server.GetDatabase(database);    //mongodb中的数据库

                var collection = db.GetCollection<T>(table);

                list = collection.FindAll().ToList();

                return list;
            }
            catch (Exception ex)
            {
                //LogHelper.WriteLog(string.Format("FindAll 失败: {0} ", ex.Message), ex);

                return list;
            }
        }
        #endregion



        #region 删除数据库/表
        public void Drop(MlevelEnum mlevel, string database = null, string table = null)
        {
            var tempdatabase = database ?? databaseName;

            var temptable = table ?? tableName;

            try
            {
                if (mlevel == MlevelEnum.tableName)
                {
                    var db = server.GetDatabase(tempdatabase);

                    db.DropCollection(temptable);
                }
                else
                {
                    server.DropDatabase(tempdatabase);
                }
            }
            catch (Exception ex)
            {
                //LogHelper.WriteLog("DropDatabase失败", ex);
            }
        }

        public CommandResult DropDataBaseOrTable(MlevelEnum mlevel, string database = null, string table = null)
        {
            BsonDocument response = new BsonDocument();

            CommandResult result = new CommandResult(response);

            var tempdatabase = database ?? databaseName;

            var temptable = table ?? tableName;

            try
            {
                if (mlevel == MlevelEnum.tableName)
                {
                    var db = server.GetDatabase(tempdatabase);

                    return db.DropCollection(temptable);
                }
                else
                {
                    return server.DropDatabase(tempdatabase);
                }
            }
            catch (Exception ex)
            {
                //LogHelper.WriteLog("DropDatabase失败", ex);
            }

            return result;
        }

        #endregion

    }

    public enum MlevelEnum
    {
        databaseName = 1,
        tableName = 2
    }
}
MongoDBHelper

 

以上是关于MongoDB基础入门003--使用官方驱动操作mongo,C#的主要内容,如果未能解决你的问题,请参考以下文章

MongoDB C# Driver 快速入门

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

MongoDB快速入门学习笔记8 MongoDB的java驱动操作

docker 003 基本操作

MongoDB简介及安装配置

MongoDB for C#基础入门