C#操作mongodb

 // 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
    }
}

 

posted on 2012-08-12 22:55  larryle  阅读(755)  评论(0编辑  收藏  举报