출처 : 본인


아래 링크는 동기방식


2015/09/14 - [프로그램 자료/Visual C#] - [C# MongoDB] MongoDBHandle 어플리케이션에서 몽고디비 써보자




MongoDB C# .Net Driver 다운 경로

http://mongodb.github.io/mongo-csharp-driver/

https://github.com/mongodb/mongo-csharp-driver/releases



사용한 DLL 파일


CSharpDriver-2.1.0-rc0.7z.001


CSharpDriver-2.1.0-rc0.7z.002




아래의 메소드를 사용하려면 사용되는 Document(T object) IEntityBase라는 인터페이스를 상속받아야 한다.

 

 

public interface IEntityBase

{

    ObjectId Id { get; set; }

 

}

 

 

public class Apple : IEntityBase

{

    public ObjectId Id { get; set; }

 

    public string Name { get; set; }

    public string Memo { get; set; }

    public int DongCode { get; set; }

    public string SiDoName { get; set; }

    public string SiGunGuName { get; set; }

}

 

이런 식으로 말이다.

 

 

using Mongo.Model;

using MongoDB.Bson;

using MongoDB.Driver;

using MongoDB.Driver.Builders;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Reflection;

using System.Text;

using System.Threading.Tasks;

 

namespace MongoWin_Async

{

    class MongoDBHandler : IDisposable

    {

        private string connString { get; set; }

 

        #region 생성자

        public MongoDBHandler(string dbName)

        {

            this.connString = string.Format("mongodb://localhost/{0}", dbName);

        }

        public MongoDBHandler(string host, string dbName, string id, string pw, int port = 27017)

        {

            this.connString = string.Format("mongodb://{0}:{1}@{2}:{3}/{4}", id, pw, host, port, dbName);

        }

        #endregion

 

        /// <summary>

        /// ObjectId Document select

        /// </summary>

        /// <typeparam name="T">Document Type</typeparam>

        /// <param name="collectionName"></param>

        /// <param name="obj"></param>

        /// <returns></returns>

        public async Task<T> SelectOne<T>(string collectionName, ObjectId id) where T : IEntityBase

        {

            try

            {

                var Collections = GetDatabase().GetCollection<T>(collectionName);

                return await Collections.Find(x => x.Id == id).SingleAsync();

            }

            catch (Exception x)

            {

                throw new Exception(x.Message);

            }

 

        }

 

        /// <summary>

        /// Document Document select(내부에선 ObjectID 동작)

        /// </summary>

        /// <typeparam name="T">Document Type</typeparam>

        /// <param name="collectionName"></param>

        /// <param name="obj"></param>

        /// <returns></returns>

        [Obsolete("해당 개체를 가지고 있으므로 사용할 필요가 없습니다.")]

        public async Task<T> SelectOne<T>(string collectionName, T obj) where T : IEntityBase

        {

            try

            {

                var Collections = GetDatabase().GetCollection<T>(collectionName);

                return await Collections.Find(x => x.Id == obj.Id).SingleAsync();

 

            }

            catch (Exception x)

            {

                throw new Exception(x.Message);

            }

 

        }

 

        /// <summary>

        /// select 함수

        /// </summary>

        /// <typeparam name="T">Document Type</typeparam>

        /// <param name="collectionName"></param>

        /// <param name="jsonFilter">Where Conditions</param>

        /// <param name="orderBy"></param>

        /// <returns></returns>

        public async Task<List<T>> Select<T>(string collectionName, string jsonFilter, Dictionary<string, MongoOrderBy> orderBy = null) where T : IEntityBase

        {

            try

            {

                var Collections = GetDatabase().GetCollection<T>(collectionName);

                if (orderBy != null)

                    return await Collections.Find(GetFilter(jsonFilter)).Sort(GetOrderBy(orderBy)).ToListAsync();

                else

                    return await Collections.Find(GetFilter(jsonFilter)).ToListAsync();

            }

            catch (Exception x)

            {

                throw new Exception(x.Message);

            }

 

        }

 

        /// <summary>

        /// Insert 함수

        /// </summary>

        /// <typeparam name="T">Document Type</typeparam>

        /// <param name="collectionName"></param>

        /// <param name="obj"></param>

        /// <returns></returns>

        public async Task Insert<T>(string collectionName, T obj) where T : IEntityBase

        {

            try

            {

                var Collections = GetDatabase().GetCollection<T>(collectionName);

                await Collections.InsertOneAsync(obj);

            }

            catch (Exception x)

            {

                throw new Exception(x.Message);

            }

        }

 

        /// <summary>

        /// ObjectID 통한 Update

        /// </summary>

        /// <typeparam name="T">Document Type</typeparam>

        /// <param name="collectionName"></param>

        /// <param name="updateItems"></param>

        /// <param name="id"></param>

        /// <returns></returns>

        public async Task<UpdateResult> UpdateById<T>(string collectionName, IDictionary<string, object> updateItems, ObjectId id) where T : IEntityBase

        {

            try

            {

                var Collections = GetDatabase().GetCollection<T>(collectionName);

                var update = new UpdateDocument { { "$set", new BsonDocument(updateItems) } };

                return await Collections.UpdateOneAsync(x => x.Id == id, update);

            }

            catch (Exception x)

            {

                throw new Exception(x.Message);

            }

        }

 

        /// <summary>

        /// Document 통한 Document Update(내부에선 ObjectID 동작)

        /// </summary>

        /// <typeparam name="T">Document Type</typeparam>

        /// <param name="collectionName"></param>

        /// <param name="obj"></param>

        /// <returns></returns>

        public async Task<ReplaceOneResult> UpdateById<T>(string collectionName, T obj) where T : IEntityBase

        {

            try

            {

                var Collections = GetDatabase().GetCollection<T>(collectionName);

                return await Collections.ReplaceOneAsync(x => x.Id == obj.Id, obj);

            }

            catch (Exception x)

            {

                throw new Exception(x.Message);

            }

        }

 

        /// <summary>

        /// 해당 Document 전체 데이터 업데이트(Id 제외, null 포함)

        /// </summary>

        /// <typeparam name="T"></typeparam>

        /// <param name="collectionName"></param>

        /// <param name="obj"></param>

        /// <param name="jsonFilter"></param>

        /// <returns></returns>

        public async Task<UpdateResult> Update<T>(string collectionName, T obj, string jsonFilter) where T : IEntityBase

        {

            try

            {

                var Collections = GetDatabase().GetCollection<T>(collectionName);

 

                Dictionary<string, object> updateItems = new Dictionary<string, object>();

                PropertyInfo[] prop = typeof(T).GetProperties();

                foreach (PropertyInfo p in prop)

                {

                    if (p.Name != "Id")

                    {

                        updateItems.Add(p.Name, p.GetValue(obj, null));

                    }

                }

 

                var update = new UpdateDocument { { "$set", new BsonDocument(updateItems) } };

                return await Collections.UpdateManyAsync(GetFilter(jsonFilter), update);

            }

            catch (Exception x)

            {

                throw new Exception(x.Message);

            }

        }

 

        /// <summary>

        /// Update 함수

        /// </summary>

        /// <typeparam name="T">Document Type</typeparam>

        /// <param name="collectionName"></param>

        /// <param name="updateItems"></param>

        /// <param name="jsonFilter">Where Conditions</param>

        /// <returns></returns>

        public async Task<UpdateResult> Update<T>(string collectionName, IDictionary<string, object> updateItems, string jsonFilter) where T : IEntityBase

        {

            try

            {

                var Collections = GetDatabase().GetCollection<T>(collectionName);

                var update = new UpdateDocument { { "$set", new BsonDocument(updateItems) } };

                return await Collections.UpdateManyAsync(GetFilter(jsonFilter), update);

            }

            catch (Exception x)

            {

                throw new Exception(x.Message);

            }

        }

 

        /// <summary>

        /// ObjectID Document Delete

        /// </summary>

        /// <typeparam name="T">Document Type</typeparam>

        /// <param name="collectionName"></param>

        /// <param name="id"></param>

        /// <returns></returns>

        public async Task<DeleteResult> DeleteById<T>(string collectionName, ObjectId id) where T : IEntityBase

        {

            try

            {

                var Collections = GetDatabase().GetCollection<T>(collectionName);

                return await Collections.DeleteOneAsync(x => x.Id == id);

            }

            catch (Exception x)

            {

                throw new Exception(x.Message);

            }

        }

 

        /// <summary>

        /// Delete 함수

        /// </summary>

        /// <typeparam name="T">Document Type</typeparam>

        /// <param name="collectionName"></param>

        /// <param name="jsonFilter">Where Conditions</param>

        /// <returns></returns>

        public async Task<DeleteResult> Delete<T>(string collectionName, string jsonFilter) where T : IEntityBase

        {

            try

            {

                var Collections = GetDatabase().GetCollection<T>(collectionName);

                return await Collections.DeleteManyAsync(GetFilter(jsonFilter));

            }

            catch (Exception x)

            {

                throw new Exception(x.Message);

            }

        }

 

        #region Private Method

 

        private IMongoDatabase GetDatabase()

        {

            var client = new MongoClient(connString);

            return client.GetDatabase(MongoUrl.Create(connString).DatabaseName);

        }

 

        private SortByDocument GetOrderBy(Dictionary<string, MongoOrderBy> orderBy)

        {

            return new SortByDocument(orderBy);

        }

 

        private PropertyInfo GetProperty(object obj, string propertyName)

        {

            Type t = obj.GetType();

            PropertyInfo prop = t.GetProperty(propertyName);

            return prop;

        }

 

        /// <summary>

        /// 해당 Document string 속성값 가져오기

        /// </summary>

        /// <param name="obj"></param>

        /// <param name="propertyName"></param>

        /// <returns></returns>

        private string GetStringValue(object obj, string propertyName)

        {

            PropertyInfo prop = GetProperty(obj, propertyName);

            return (string)prop.GetValue(obj, null);

        }

        /// <summary>

        /// 해당 Document int 속성값 가져오기

        /// </summary>

        /// <param name="obj"></param>

        /// <param name="propertyName"></param>

        /// <returns></returns>

        private int GetIntValue(object obj, string propertyName)

        {

            PropertyInfo prop = GetProperty(obj, propertyName);

            return (int)prop.GetValue(obj, null);

        }

        /// <summary>

        /// Document ID 가져오기

        /// </summary>

        /// <param name="obj"></param>

        /// <param name="propertyName">Id</param>

        /// <returns></returns>

        private ObjectId GetId(object obj)

        {

            ObjectId id;

            try

            {

                PropertyInfo prop = GetProperty(obj, "Id");

                id = (ObjectId)prop.GetValue(obj, null);

            }

            catch

            {

                id = new ObjectId();

            }

            return id;

        }

        private QueryDocument GetFilter(string jsonFilter)

        {

            return new QueryDocument(BsonDocument.Parse(jsonFilter));

        }

 

        #endregion

 

        public void Dispose()

        {

            GC.SuppressFinalize(this);

        }

    }

    public enum MongoOrderBy

    {

        Ascending = 1,

        Descending = -1

    }

}

 

 

 













Posted by motolies
,