• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C#操作mongodb

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
 // MongoDB连接串,以[mongodb://]开头。这里,我们连接的是本机的服务
            string connectionString = "mongodb://192.168.1.170";
            // 连接到一个MongoServer上
            MongoServer server = MongoServer.Create(connectionString);
            MongoDatabase db = server.GetDatabase("test");
            MongoCollection collection = db.GetCollection("user");
            // 创建一个employee
            BsonDocument employee = new BsonDocument{
                                      { "name", "zhangsan" },
                                      { "title", "hello" },
                                      { "description", "hi"}
                                   };
            collection.Insert(employee);

            var query = new QueryDocument("name", "entlib.com");
            foreach (BsonDocument emp in collection.FindAs<BsonDocument>(query))
            {
                // BsonValue有两种取值方式,一个是AsXXX,一个是ToXXX
                System.Diagnostics.Debug.WriteLine(string.Format("name:{0}\title:{1}\tdesc:{2}\tcount:{3}",
                emp["name"].AsString, emp["title"].ToString(),
                emp["description"].AsString,
                collection.Count().ToString()));
            }

            System.Diagnostics.Debug.Write("------end-----");
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MongoDB.Driver;
using MongoDB.Bson;
using MongoDB.Driver.Builders;
using NUnit.Framework;

namespace MongoDBHelper
{
    [TestFixture]
    public class MongoDBHelper : Base
    {
        protected static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(Base));

        private static string databaseName
        {
            get { return System.Configuration.ConfigurationManager.AppSettings["mongodb_database"]; }
        }

        #region 初始化MongoServer
        /// <summary>
        /// 初始化MongoServer
        /// </summary>
        private static MongoServer server
        {
            get
            {
                if (System.Configuration.ConfigurationManager.AppSettings["mongodb_state"] == "1")
                    return MongoServer.Create(System.Configuration.ConfigurationManager.AppSettings["mongodb_connectionstring"]);
                else
                    return null;
            }
        }
        #endregion

        #region  获取当前MongoDatabase
        /// <summary>
        /// 获取当前MongoDatabase
        /// </summary>
        private static MongoDatabase database
        {
            get
            {
                if (server == null) return null;
                server.Connect(TimeSpan.FromSeconds(5));
                if (!server.DatabaseExists(databaseName))
                {
                    var databaseSettings = server.CreateDatabaseSettings(databaseName);
                    return server.GetDatabase(databaseSettings);
                }
                else
                {
                    return server.GetDatabase(databaseName);
                }
            }
        }
        #endregion

        #region 获取当前MongoCollection
        /// <summary>
        /// 获取当前MongoCollection
        /// </summary>
        /// <param name="collectionName"></param>
        /// <returns></returns>
        public static MongoCollection<BsonDocument> GetMongoCollections(string collectionName)
        {
            if (server == null) return null;
            using (server.RequestStart(database))//开始连接数据库。
            {
                if (!database.CollectionExists(collectionName))
                {
                    database.CreateCollection(collectionName);
                }
                return database.GetCollection<BsonDocument>(collectionName);
            }
        }
        #endregion

        #region 插入
        /// <summary>
        /// Insert(Entity)
        /// </summary>
        /// <typeparam name="T">Entity</typeparam>
        /// <param name="collectionName">collectionName</param>
        /// <param name="entity">Entity</param>
        /// <returns>SafeModeResult</returns>
        public static SafeModeResult InsertOne<T>(string collectionName, T entity)
        {
            try
            {
                MongoCollection collection = GetMongoCollections(collectionName);
                return collection != null ? collection.Insert(entity) : null;
            }
            catch (Exception ex)
            {
                logger.Error(ex); return null;
            }
        }

        /// <summary>
        /// Insert(List)
        /// </summary>
        /// <typeparam name="T">Entity</typeparam>
        /// <param name="collectionName">collectionName</param>
        /// <param name="entitys">IEnumerable</param>
        /// <returns>IEnumerable<SafeModeResult></returns>
        public static IEnumerable<SafeModeResult> Insert<T>(string collectionName, IEnumerable<T> list)
        {
            try
            {
                MongoCollection collection = GetMongoCollections(collectionName);
                return collection != null ? collection.InsertBatch<T>(list) : null;
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return null;
            }
        }

        #endregion

        #region 更新
        /// <summary>
        /// Update(Entity)
        /// </summary>
        /// <typeparam name="T">Entity</typeparam>
        /// <param name="collectionName">collectionName</param>
        /// <param name="entity">Entity</param>
        /// <returns>SafeModeResult</returns>
        public static SafeModeResult Update<T>(string collectionName, T entity)
        {
            try
            {
                MongoCollection collection = GetMongoCollections(collectionName);
                return collection != null ? collection.Save(entity) : null;
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return null;
            }
        }
        /// <summary>
        /// Update(Query,Update)
        /// </summary>
        /// <param name="collectionName">collectionName</param>
        /// <param name="query">query</param>
        /// <param name="update">update</param>
        /// <returns>SafeModeResult</returns>
        public static SafeModeResult Update(string collectionName, IMongoQuery query, IMongoUpdate update)
        {
            try
            {
                MongoCollection collection = GetMongoCollections(collectionName);
                return collection != null ? collection.Update(query, update, UpdateFlags.Multi) : null;
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return null;
            }
        }

        /// <summary>
        /// Update(Query,Update)
        /// </summary>
        /// <param name="dic_EQ">Query</param>
        /// <param name="dic_Set">Update</param>
        /// <param name="collectionname">collection</param>
        /// <returns>SafeModeResult</returns>
        public static SafeModeResult Update(Dictionary<string, BsonValue> dic_Query, Dictionary<string, BsonValue> dic_Set, string collectionName)
        {
            QueryDocument query = new QueryDocument(dic_Query);
            UpdateBuilder updatebuilder = new UpdateBuilder();
            foreach (var item in dic_Set)
            {
                updatebuilder.Set(item.Key, item.Value);
            }
            return Update(collectionName, query, updatebuilder);
        }
        #endregion

        #region 删除
        /// <summary>
        /// Delete(Query)
        /// </summary>
        /// <param name="dic">Query</param>
        /// <param name="collectionName">collectionName</param>
        /// <returns></returns>
        public static SafeModeResult Delete(Dictionary<string, BsonValue> dic, string collectionName)
        {
            QueryDocument query = new QueryDocument(dic);
            return Delete(query, collectionName);
        }

        /// <summary>
        /// Delete(Query)
        /// </summary>
        /// <param name="dic">键值对query</param>
        /// <param name="collectionName">collectionName</param>
        /// <returns></returns>
        public static SafeModeResult Delete(IMongoQuery query, string collectionName)
        {
            try
            {
                MongoCollection collection = GetMongoCollections(collectionName);
                return collection != null ? collection.Remove(query) : null;
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return null;
            }
        }
        #endregion

        #region 查询
        /// <summary>
        /// Select
        /// </summary>
        /// <typeparam name="T">Entity</typeparam>
        /// <param name="collectionName">collectionName</param>
        /// <param name="dic">Query</param>
        /// <returns>Entity</returns>
        public static T GetOne<T>(string collectionName, Dictionary<string, BsonValue> dic)
        {
            QueryDocument query = new QueryDocument(dic);
            return GetOne<T>(collectionName, query);
        }
        public static T GetOne<T>(string collectionName, IMongoQuery query)
        {
            try
            {
                MongoCollection collection = GetMongoCollections(collectionName);
                return collection != null ? collection.FindOneAs<T>(query) : default(T);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return default(T);
            }
        }

        /// <summary>
        /// 查询集合List
        /// </summary>
        /// <typeparam name="T">T</typeparam>
        /// <param name="collectionName">collectionName</param>
        /// <param name="dic">Dictionary</param>
        /// <returns></returns>
        public static List<T> GetList<T>(string collectionName, Dictionary<string, BsonValue> dic)
        {
            QueryDocument query = new QueryDocument(dic);
            return GetList<T>(collectionName, query);
        }

        /// <summary>
        /// 查询集合List
        /// </summary>
        /// <typeparam name="T">T</typeparam>
        /// <param name="collectionName">collectionName</param>
        /// <param name="dic">Dictionary</param>
        /// <returns></returns>
        public static List<T> GetList<T>(string collectionName, IMongoQuery query)
        {
            try
            {
                MongoCollection collection = GetMongoCollections(collectionName);
                return collection != null ? collection.FindAs<T>(query).ToList() : null;
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return null;
            }
        }

        /// <summary>
        /// 查询分页信息
        /// </summary>
        /// <typeparam name="T">T</typeparam>
        /// <param name="pagesize">pageSize</param>
        /// <param name="pageindex">pageindex</param>
        /// <param name="collectionName">collectionName</param>
        /// <param name="query_dic">query_dic</param>
        /// <param name="sortBy_dic">sortBy_dic</param>
        /// <param name="fields_dic">fields_dic</param>
        /// <returns></returns>
        public static List<T> GetPageInfo<T>(int pagesize, int pageindex, string collectionName, Dictionary<string, BsonValue> query_dic, string[] sortBy_dic, string[] fields_dic)
        {
            QueryDocument query = new QueryDocument(query_dic);
            IMongoSortBy sort = SortBy.Descending(sortBy_dic);
            IMongoFields field = Fields.Include(fields_dic);
            return GetPageInfo<T>(collectionName, query, pagesize, pageindex, sort, field);
        }

        public static List<T> GetPageInfo<T>(string collectionName, IMongoQuery query, int pagesize, int pageindex, IMongoSortBy sortBy, IMongoFields fields)
        {
            try
            {
                MongoCollection collection = GetMongoCollections(collectionName);
                if (collection != null)
                {
                    MongoCursor<T> myCursor;
                    myCursor = query != null
                                   ? collection.FindAs<T>(query)
                                   : collection.FindAllAs<T>();
                    myCursor = sortBy != null ? myCursor.SetSortOrder(sortBy) : myCursor;
                    myCursor = fields != null ? myCursor.SetFields(fields) : myCursor;
                    return myCursor.SetSkip((pageindex - 1) * pagesize).SetLimit(pagesize).ToList<T>();
                }
                return null;
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return null;
            }
        }

        #endregion
    }
}

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
链表反序(C#版)发布时间:2022-07-18
下一篇:
(教学思路c#之面向对象二)初步理解面向对象的基本概念发布时间:2022-07-18
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap