출처 : 본인
동기메소드 방식...
비동기는 아래 링크로.
2015/09/16 - [프로그램 자료/Visual C#] - [C# MongoDB] MongoDBHandle 어플리케이션에서 몽고디비 써보자 2.0 Driver
.net Driver 1.10.1 버전인 DLL 가지고 작업함.....
출처 : https://github.com/mongodb/mongo-csharp-driver/releases
using System;
using System.Collections.Generic;
using System.Linq;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using System.Reflection;
namespace MongoWin_Sync
{
public class MongoDBHandle : IDisposable
{
private string connString { get; set; }
#region 생성자
public MongoDBHandle(string dbName)
{
this.connString = string.Format("mongodb://localhost/{0}", dbName);
}
public MongoDBHandle(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 검색
/// </summary>
/// <typeparam name="T">Document Type</typeparam>
/// <param name="collectionName"></param>
/// <param name="id"></param>
/// <returns></returns>
public T SelectOne<T>(string collectionName, ObjectId id)
{
object rtn = null;
try
{
var Collections = GetDatabase().GetCollection<T>(collectionName);
IMongoQuery query = Query.EQ("_id", id);
var result = Collections.Find(query).SingleOrDefault();
if (result != null)
{
rtn = result;
}
}
catch (Exception x)
{
throw new Exception(x.Message);
}
return (T)Convert.ChangeType(rtn, typeof(T));
}
/// <summary>
/// Document로 Document 검색(내부에선 ObjectID로 동작)
/// </summary>
/// <typeparam name="T">Document Type</typeparam>
/// <param name="collectionName"></param>
/// <param name="id"></param>
/// <returns></returns>
public T SelectOne<T>(string collectionName, T obj)
{
object rtn = null;
try
{
var Collections = GetDatabase().GetCollection<T>(collectionName);
ObjectId _id = GetId(obj);
if (_id != new ObjectId())
{
IMongoQuery query = Query.EQ("_id", _id);
var result = Collections.Find(query).SingleOrDefault();
if (result != null)
{
rtn = result;
}
}
}
catch (Exception x)
{
throw new Exception(x.Message);
}
return (T)Convert.ChangeType(rtn, typeof(T));
}
/// <summary>
/// select 함수
/// </summary>
/// <typeparam name="T">Document Type</typeparam>
/// <param name="collectionName"></param>
/// <param name="jsonParam">Where Conditions</param>
/// <param name="orderBy"></param>
/// <returns></returns>
public List<T> Select<T>(string collectionName, string jsonParam, Dictionary<string, MongoOrderBy> orderBy = null)
{
List<T> list = new List<T>();
try
{
var Collections = GetDatabase().GetCollection<T>(collectionName);
MongoCursor<T> result = null;
if (orderBy != null)
result = Collections.Find(GetWhere(jsonParam)).SetSortOrder(GetOrderBy(orderBy));
else
result = Collections.Find(GetWhere(jsonParam));
foreach (var item in result)
{
list.Add(item);
}
}
catch (Exception x)
{
throw new Exception(x.Message);
}
return list;
}
/// <summary>
/// insert 함수
/// </summary>
/// <typeparam name="T">Document Type</typeparam>
/// <param name="collectionName"></param>
/// <param name="obj"></param>
/// <returns></returns>
public bool Insert<T>(string collectionName, T obj)
{
bool status = false;
try
{
var Collections = GetDatabase().GetCollection<T>(collectionName);
var result = Collections.Insert(obj);
//status = result.Ok;
ObjectId id = GetId(obj);
}
catch (Exception x)
{
throw new Exception(x.Message);
}
return status;
}
/// <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 bool UpdateById<T>(string collectionName, IDictionary<string, object> updateItems, ObjectId id)
{
bool status = false;
try
{
var Collections = GetDatabase().GetCollection<T>(collectionName);
IMongoQuery query = Query.EQ("_id", id);
IMongoUpdate update = new UpdateDocument { { "$set", new BsonDocument(updateItems) } };
Collections.Update(query, update);
status = true;
}
catch (Exception x)
{
throw new Exception(x.Message);
}
return status;
}
/// <summary>
/// Document를 통한 Document Update(내부에선 ObjectID로 동작)
/// </summary>
/// <typeparam name="T">Document Type</typeparam>
/// <param name="collectionName"></param>
/// <param name="obj"></param>
/// <returns></returns>
public bool UpdateById<T>(string collectionName, T obj)
{
bool status = false;
try
{
var Collections = GetDatabase().GetCollection<T>(collectionName);
ObjectId _id = GetId(obj);
if (_id != new ObjectId())
{
Collections.Save(obj);
status = true;
}
}
catch (Exception x)
{
throw new Exception(x.Message);
}
return status;
}
/// <summary>
/// 해당 Document로 업데이트(Id 제외)
/// </summary>
/// <typeparam name="T">Document Type</typeparam>
/// <param name="collectionName"></param>
/// <param name="obj"></param>
/// <param name="jsonParam">Where Conditions</param>
/// <returns></returns>
public bool UpdateByDocument<T>(string collectionName, T obj, string jsonParam)
{
bool status = false;
try
{
var Collections = GetDatabase().GetCollection<T>(collectionName);
IMongoQuery query = GetWhere(jsonParam);
Dictionary<string, object> upItems = new Dictionary<string, object>();
PropertyInfo[] prop = typeof(T).GetProperties();
foreach (PropertyInfo p in prop)
{
if (p.Name != "Id" && p.GetValue(obj, null) != null)
{
upItems.Add(p.Name, p.GetValue(obj, null));
}
}
IMongoUpdate update = new UpdateDocument { { "$set", new BsonDocument(upItems) } };
Collections.Update(query, update, UpdateFlags.Multi);
status = true;
}
catch (Exception x)
{
throw new Exception(x.Message);
}
return status;
}
/// <summary>
/// Update
/// </summary>
/// <typeparam name="T">Document Type</typeparam>
/// <param name="collectionName"></param>
/// <param name="updateItems"></param>
/// <param name="jsonParam">Where Conditions</param>
/// <returns></returns>
public bool Update<T>(string collectionName, IDictionary<string, object> updateItems, string jsonParam)
{
bool status = false;
try
{
var Collections = GetDatabase().GetCollection<T>(collectionName);
IMongoQuery query = GetWhere(jsonParam);
IMongoUpdate update = new UpdateDocument { { "$set", new BsonDocument(updateItems) } };
Collections.Update(query, update, UpdateFlags.Multi);
status = true;
}
catch (Exception x)
{
throw new Exception(x.Message);
}
return status;
}
/// <summary>
/// ObjectID로 Document 삭제
/// </summary>
/// <typeparam name="T">Document Type</typeparam>
/// <param name="collectionName"></param>
/// <param name="id"></param>
/// <returns></returns>
public bool DeleteById<T>(string collectionName, ObjectId id)
{
bool status = false;
try
{
var Collections = GetDatabase().GetCollection<T>(collectionName);
IMongoQuery query = Query.EQ("_id", id);
Collections.Remove(query);
status = true;
}
catch (Exception x)
{
throw new Exception(x.Message);
}
return status;
}
/// <summary>
/// Document로 Document 삭제(내부에선 ObjectID로 동작)
/// </summary>
/// <typeparam name="T">Document Type</typeparam>
/// <param name="collectionName"></param>
/// <param name="obj"></param>
/// <returns></returns>
public bool DeleteByDocument<T>(string collectionName, T obj)
{
bool status = false;
try
{
var Collections = GetDatabase().GetCollection<T>(collectionName);
ObjectId _id = GetId(obj);
if (_id != new ObjectId())
{
IMongoQuery query = Query.EQ("_id", _id);
Collections.Remove(query);
status = true;
}
}
catch (Exception x)
{
throw new Exception(x.Message);
}
return status;
}
/// <summary>
/// Delete
/// </summary>
/// <typeparam name="T">Document Type</typeparam>
/// <param name="collectionName"></param>
/// <param name="jsonParam">Where Conditions</param>
/// <returns></returns>
public bool Delete<T>(string collectionName, string jsonParam)
{
bool status = false;
try
{
var Collections = GetDatabase().GetCollection<T>(collectionName);
IMongoQuery query = GetWhere(jsonParam);
Collections.Remove(query);
status = true;
}
catch (Exception x)
{
throw new Exception(x.Message);
}
return status;
}
#region Private Method
private MongoDatabase GetDatabase()
{
var client = new MongoClient(connString);
return client.GetServer().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 GetWhere(string jsonParam)
{
return new QueryDocument(BsonDocument.Parse(jsonParam));
}
#endregion
public void Dispose()
{
GC.SuppressFinalize(this);
}
}
public enum MongoOrderBy
{
Ascending = 1,
Descending = -1
}
}