C# 操作mongodb 简单实例

  本实例主要简单的查询,新增,修改和删除操作,完整代码如下:

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


namespace mongoDbOper
{
    public class DBHelper
    {
        /// <summary>
        /// mongodb数据库连接字符串
        /// </summary>
        private static string dbConnectStr = "mongodb://127.0.0.1:27017";
        /// <summary>
        /// 指定的数据库
        /// </summary>
        private static string dbName = "OTT_DB";
        /// <summary>
        /// 展会信息表
        /// </summary>
        private static string tbNameM = "Meeting";
        /// <summary>
        /// 行业资讯表
        /// </summary>
        private static string tbNameC = "Information";
        /// <summary>
        /// 订阅用户表
        /// </summary>
        private static string tbNameUser = "User";
        /// <summary>
        /// 已发送展会信息表
        /// </summary>
        private static string tbNameMCK = "MeetingCK";
        /// <summary>
        /// 已发送行业资讯表
        /// </summary>
        private static string tbNameICK = "InfoCK";

        private static MongoDatabase db = null;

        /// <summary>
        /// 用户审核通过
        /// </summary>
        private static string userPass = "通过";
        /// <summary>
        /// 用户未审核通过,待审核
        /// </summary>
        private static string userNoPass = "审核";
        /// <summary>
        /// 初始化mongodb数据库
        /// </summary>
        public static void InitDB()
        {
            var connStr = string.IsNullOrEmpty(ConfigurationManager.AppSettings["mongodbServer"]) ? dbConnectStr : ConfigurationManager.AppSettings["mongodbServer"].ToString();

            userPass = string.IsNullOrEmpty(ConfigurationManager.AppSettings["pass"]) ? userPass : ConfigurationManager.AppSettings["pass"].ToString();
            userNoPass = string.IsNullOrEmpty(ConfigurationManager.AppSettings["pass"]) ? userNoPass : ConfigurationManager.AppSettings["nonpass"].ToString();

            //创建数据连接  
            //var server = MongoServer.Create(connStr);
            var server = new MongoClient(connStr).GetServer();
            //获取指定数据库
            db = server.GetDatabase(dbName);
        }


       

        #region 获取最近三个月的会议活动
        /// <summary>
        /// 获取最近三个月的会议活动
        /// </summary>
        public static void GetMeeting()
        {
            if (db == null)
            {
                InitDB();
            }
            string startdate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
            string enddate = DateTime.Now.AddDays(90).ToString("yyyy-MM-dd");

            MongoCollection<Meeting> col = db.GetCollection<Meeting>("Meeting");
            var result = col.FindAll().Where(a => Convert.ToDateTime(a.startdate) > Convert.ToDateTime(startdate) &&
                Convert.ToDateTime(a.enddate) <= Convert.ToDateTime(enddate));

            var lst = new List<Meeting>();
            foreach (Meeting info in result)
            {
                info.ID = info.Id.ToString();
                lst.Add(info);
            }
            var json = lst.ToJson();

            Console.WriteLine(json);
            Console.Read();
        }
        #endregion

        #region 保存新订阅用户信息
        /// <summary>
        /// 保存新订阅用户信息
        /// </summary>
        /// <param name="user">要保存的用户信息实体</param>
        /// <param name="tbName">表名,默认:User</param>
        /// <returns>返回bool ,true保存成功;false保存失败</returns>
        public static bool InsertUser(User user = null, String tbName = "User")
        {
            if (db == null)
            {
                InitDB();
            }
            User user1 = new User();
            user1.name = "test";
            user1.email = "test@ctrchina.cn";
            user1.tel = "13388989998";
            user1.company = "CTR";
            user1.position = "总监";
            user1.isPass = "通过";
            MongoCollection<User> col = db.GetCollection<User>(tbName);
            WriteConcernResult result = col.Insert(user1);
            Console.WriteLine(result.Ok);
            Console.Read();
            return result.Ok;
        }
        #endregion

        #region 修改订阅用户信息
        /// <summary>
        /// 修改订阅用户信息
        /// </summary>
        /// <param name="user">订阅用户信息实体</param>
        /// <param name="tbName">表名,默认是User</param>
        /// <returns>返回bool ,true:修改成功;false:修改失败</returns>
        public static bool UpdateUser(User user = null, String tbName = "User")
        {
            if (db == null)
            {
                InitDB();
            }
            if (user == null)
            {
                user = new User();
                user.Id = new ObjectId("5965dfd22ed9257eccc36494");
                user.position = "总经理111总监";
                user.tel = "166677777777";
            }
            MongoCollection<User> col = db.GetCollection<User>(tbName);
            BsonDocument userSave = BsonExtensionMethods.ToBsonDocument(user);

            IMongoQuery query = Query.EQ("_id", user.Id);

            WriteConcernResult result = col.Update(query, new UpdateDocument(userSave));
            Console.WriteLine(result.Ok);
            Console.Read();
            return result.Ok;
        }
        #endregion

        #region 删除订阅用户信息
        /// <summary>
        /// 删除订阅用户信息
        /// </summary>
        /// <param name="id">信息ID(唯一)</param>
        /// <param name="tbName">表名,默认是User</param>
        /// <returns>返回bool ,true:删除成功;fals:e删除失败</returns>
        public static bool DeleteUser(String id = "5965dfd22ed9257eccc36494", String tbName = "User")
        {
            if (db == null)
            {
                InitDB();
            }
            MongoCollection<Information> col = db.GetCollection<Information>(tbName);
            IMongoQuery query = Query.EQ("_id", new ObjectId(id));

            WriteConcernResult result = col.Remove(query);
            Console.WriteLine(result.Ok);
            Console.Read();
            return result.Ok;
        }
        #endregion

    }
}

 

posted on 2017-07-12 16:21  shaomine  阅读(2295)  评论(0编辑  收藏  举报