mongodb的C#封装,驱动是samus/mongodb-csharp
1.连接类
using MongoDB; using MongoDB.Linq; namespace DBModel { public class ConnString { public static string m_connStr = System.Configuration.ConfigurationManager.AppSettings["mongodb_ip"];// "Server=127.0.0.1"; public static string m_dbName = System.Configuration.ConfigurationManager.AppSettings["mongodb_db"];//"DYZS_DB"; } //对某个表的操作 public class MongoDatabase : IDisposable { private Mongo m_mongo; private IMongoDatabase m_db; private IMongoCollection<Document> m_Collection; public string m_msg = string.Empty; public bool bOpen = false; public MongoDatabase() { if (string.IsNullOrEmpty(ConnString.m_connStr)) throw new ArgumentNullException("connectionString"); m_mongo = new Mongo(ConnString.m_connStr); // 立即连接 MongoDB m_mongo.Connect(); bOpen = true; if (string.IsNullOrEmpty(ConnString.m_dbName) == false) m_db = m_mongo.GetDatabase(ConnString.m_dbName); } public MongoDatabase(string tableName) { if (string.IsNullOrEmpty(ConnString.m_connStr)) throw new ArgumentNullException("connectionString"); m_mongo = new Mongo(ConnString.m_connStr); // 立即连接 MongoDB m_mongo.Connect(); bOpen = true; if (string.IsNullOrEmpty(ConnString.m_dbName) == false) m_db = m_mongo.GetDatabase(ConnString.m_dbName); m_Collection = m_db.GetCollection<Document>(tableName) as MongoCollection<Document>; } public void Dispose() { if (m_mongo != null) { if (bOpen) { m_mongo.Disconnect(); bOpen = false; } m_mongo.Dispose(); m_mongo = null; } } public void SetCollection(string tableName) { m_Collection = m_db.GetCollection<Document>(tableName) as MongoCollection<Document>; } // 获取当前连接数据库的指定集合【根据指定名称】 public IMongoCollection GetCollection(string name) { return this.m_db.GetCollection(name); } // 获取当前连接数据库的指定集合【依据类型】 public IMongoCollection<T> GetCollection<T>() where T : class { return this.m_db.GetCollection<T>(); } public Document Find(object value, string key = "_id") { return m_Collection.FindOne(new Document{{ key, value}}); } public Document Find(Document query) { return m_Collection.FindOne(query); } public long Count(Document query) { return m_Collection.Count(query); } public void Delete(string value, string key = "_id") { m_Collection.Remove(new Document{{ key, value}}); } public void Delete(Document query) { m_Collection.Remove(query); } //db.ids .findAndModify({update:{$inc:{'id':1}}, query:{"name":"user"}, new:true}); //modify a document (at most one) and return it //有点慢 public Document FindAndModify(Document query, Document set) { return m_Collection.FindAndModify(set, query, true); } public int Save(Document query, Document doc) { try { string _id = UtilData.toString(doc["_id"]); if (_id == string.Empty)//如果没有_id { _id = MongoDB.Oid.NewOid().ToString(); } if (m_Collection.FindOne(query) == null) { doc["_id"] = _id; m_Collection.Insert(doc); } else { doc["_id"] = _id; m_Collection.Save(doc); } } catch { ; } ; } //1.update方法如果是要更新文档中的一个或几个属性的时候,必须要用形如{$set:{age:33}}的形式,否则被覆盖。 //2.update方法默认是只更新找到的第一个文档,如果需要所有的文档都更新,则需要在option部分再加上{multi:true}, //如果想要在查找不到这条记录的时候新增一条,则要在option部分加上{upsert:true}。 public int Update(Document query, Document set) { try { m_Collection.Update(set, query); } catch { ; } ; } public int UpdateAll(Document query, Document set) { try { m_Collection.Update(set, query,UpdateFlags.MultiUpdate); } catch { ; } ; } //新建 public string Insert(Document doc, string key = "_id") { string id = UtilData.toString(doc[key]); if (id == string.Empty) { id = MongoDB.Oid.NewOid().ToString(); doc[key] = id; } m_Collection.Save(doc); return id; } } }
2.表操作基类
public class MongoBasicOper { public string m_TableName = string.Empty; public string m_Msg = string.Empty; public MongoBasicOper() { } public MongoBasicOper(string table) { m_TableName = table; } public void SetTable(string table) { m_TableName = table; } public Document GetRow(object value, string key = "_id") { using (MongoDatabase mongo = new MongoDatabase(m_TableName)) { return mongo.Find(value, key); } } public Document GetRow(Document query) { using (MongoDatabase mongo = new MongoDatabase(m_TableName)) { return mongo.Find(query); } } public long Count(Document query) { using (MongoDatabase mongo = new MongoDatabase(m_TableName)) { return mongo.Count(query); } } public string Insert(Document doc) { if (UtilData.toString(doc["_id"]) == string.Empty) { string id = MongoDB.Oid.NewOid().ToString(); doc["_id"] = id; } MongoDatabase mongo = null; try { mongo = new MongoDatabase(m_TableName); mongo.Insert(doc); } catch(Exception e) { m_Msg = e.Message; return null; } finally { mongo.Dispose(); } return UtilData.toString(doc["_id"]); } //不需要加update,需要加$set public Document FindAndModify(Document query, Document set) { using (MongoDatabase mongo = new MongoDatabase(m_TableName)) { return mongo.FindAndModify(query, set); } } //有则替换,无则插入 public int Save (string _id, Document doc) { using (MongoDatabase mongo = new MongoDatabase(m_TableName)) { return mongo.Save(new Document("_id",_id),doc); } } //有则替换,无则插入 public int Save(Document query, Document doc) { using (MongoDatabase mongo = new MongoDatabase(m_TableName)) { return mongo.Save(query,doc); } } //替换 public int Replace(string _id, Document doc) { using (MongoDatabase mongo = new MongoDatabase(m_TableName)) { return mongo.Update(new Document() { { "_id", _id } }, doc); } } //部分更新,单行 public int Set(string _id, Document doc) { using (MongoDatabase mongo = new MongoDatabase(m_TableName)) { Document set = new Document(); set.Add("$set", doc); return mongo.Update(new Document(){ {"_id",_id} }, set); } } //部分更新,多行 public int Set(Document query, Document doc) { using (MongoDatabase mongo = new MongoDatabase(m_TableName)) { Document set = new Document(); set.Add("$set", doc); return mongo.UpdateAll(query, set); } } //创建 public string Insert(Document doc, string key = "_id") { using (MongoDatabase mongo = new MongoDatabase(m_TableName)) { return mongo.Insert(doc, key); } } //keyVal是查找值 , string key = "_id") { Document query = new Document(key, keyVal); Document doc = new Document(colName, addVal); Document docInc = new Document("$inc", doc); var row = FindAndModify(query, docInc); if (row == null) { query.Add(colName, addVal); Insert(query); row = GetRow(keyVal, key); } ; UtilData.toInt(row[colName], ref val); return val; } public void Delete(string val) { using (MongoDatabase mongo = new MongoDatabase(m_TableName)) { mongo.Delete(val); } } public void Delete(Document query) { using (MongoDatabase mongo = new MongoDatabase(m_TableName)) { mongo.Delete(query); } } //page从1开始 public List<Document> GetList(List<string> lstColName, Document query, JqGridParam jqParam, ref int count) { Document sort = new Document(); jqParam.sidx = UtilData.toString(jqParam.sidx); jqParam.sord = UtilData.toString(jqParam.sord); if (jqParam.sidx == string.Empty) { jqParam.sidx = "Time"; } var arrIndex = jqParam.sidx.Split(','); int[] arrSort = new int[arrIndex.Length]; ; i < arrSort.Length; i++) { sort.Add(arrIndex[i], -); } if (!string.IsNullOrEmpty(jqParam.sord)) { var arr2 = jqParam.sord.Split(','); ; i < arr2.Length; i++) { if (i >= arrSort.Length) break; ") { sort[arrIndex[i]] = ; } } } return GetList(lstColName,query,sort,jqParam, ref count); } public List<Document> GetList(List<string> lstColName, Document query, Document sort, JqGridParam jqParam, ref int count) { List<Document> lstRes = new List<Document>(); using (MongoDatabase mongo = new MongoDatabase(m_TableName)) { IMongoCollection collection = mongo.GetCollection(m_TableName);//打开db数据库中的table表 count = (int)collection.Count(query); ) { jqParam.page = ; } && count <= (jqParam.page - ) * jqParam.rows) { jqParam.page = ( ? : ); } ) { ) { jqParam.page = ; } ) { jqParam.page = (int)Math.Ceiling((float)count / (float)jqParam.rows); } ) * jqParam.rows).Limit(jqParam.rows); string colName = string.Empty; foreach (Document docx in cursor2.Documents) { Document doc = new Document(); ; i < lstColName.Count; i++) { colName = lstColName[i]; doc[colName] = docx[colName]; } lstRes.Add(doc); } } } return lstRes; } public List<Document> GetTopRow(List<string> lstColName, Document query, Document sort, int top) { List<Document> lstRes = new List<Document>(); using (MongoDatabase mongo = new MongoDatabase(m_TableName)) { IMongoCollection collection = mongo.GetCollection(m_TableName);//打开db数据库中的table表 ICursor cursor; ) { cursor = collection.Find(query).Sort(sort).Limit(top); } else { if (sort == null) { cursor = collection.Find(query); } else { cursor = collection.Find(query).Sort(sort); } } string colName = string.Empty; foreach (Document docx in cursor.Documents) { Document doc = new Document(); ; i < lstColName.Count; i++) { colName = lstColName[i]; doc[colName] = docx[colName]; } lstRes.Add(doc); } } return lstRes; } //方便前台处理,全部转换为string类型 public List<Document> GetListEx(List<string> lstColName, Document query, JqGridParam jqParam, ref int count) { var lstRes = GetList(lstColName, query, jqParam, ref count); string colName = string.Empty; foreach (Document doc in lstRes) { ; i < lstColName.Count; i++) { colName = lstColName[i]; doc[colName] = UtilData.toView(doc[colName]); } } return lstRes; } //public ICursor GetList(int rows, int page, ref int count) //{ // using (MonDB mongo = new MonDB(m_TableName)) // { // var collection = mongo.GetCollection<Customer>(); // var query2 = from c in collection.Linq() // where c._id == "1" // select c; // count = query2.Count(); // return query2.Skip(rows * page - 1).Take(rows).ToList(); //IMongoCollection col = db.GetCollection("table");//打开db数据库中的table表 //ICursor cur = col.Find(query).Skip(10).Limit(100);//从第10条记录开始查询每页显示100条 //foreach (Document docx in cur.Documents) //{ //Response.Write(docx["id"]+"</br>"); //} // } //} }
3.查询封装类
public class DocOP : Document { /// <summary> /// Initializes a new instance of the <see cref="DocOP"/> class. /// </summary> /// <remarks>Only allow instantiation through static methods.</remarks> private DocOP() { } /// <summary> /// Matches an object which is greater than the specified value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value">The value.</param> /// <returns></returns> public static DocOP GreaterThan<T>(T value) { return (DocOP)new DocOP().Add("$gt", value); } /// <summary> /// Matches an object which is greater than or equal to the specified value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value">The value.</param> /// <returns></returns> public static DocOP GreaterThanOrEqual<T>(T value) { return (DocOP)new DocOP().Add("$gte", value); } /// <summary> /// Matches an object which is less than the specified value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value">The value.</param> /// <returns></returns> public static DocOP LessThan<T>(T value) { return (DocOP)new DocOP().Add("$lt", value); } /// <summary> /// Matches an object which is less than or equal to the specified value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value">The value.</param> /// <returns></returns> public static DocOP LessThanOrEqual<T>(T value) { return (DocOP)new DocOP().Add("$lte", value); } /// <summary> /// Matches an object which does not equal the specified value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value">The value.</param> /// <returns></returns> public static DocOP NotEqual<T>(T value) { return (DocOP)new DocOP().Add("$ne", value); } /// <summary> /// Matches an array which has one of the specified values. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="values">The values.</param> /// <returns></returns> public static DocOP In<T>(params T[] values) { return (DocOP)new DocOP().Add("$in", values); } /// <summary> /// Matches an array which does not have any of the specified values. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="values">The values.</param> /// <returns></returns> public static DocOP NotIn<T>(params T[] values) { return (DocOP)new DocOP().Add("$nin", values); } /// <summary> /// Matches an array which has all of the specified values. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="values">The values.</param> /// <returns></returns> public static DocOP All<T>(params T[] values) { return (DocOP)new DocOP().Add("$all", values); } /// <summary> /// Modulus operator. /// </summary> /// <param name="denominator">The denominator.</param> /// <param name="result">The result.</param> /// <returns></returns> public static DocOP Mod(int denominator, int result) { return (DocOP)new DocOP().Add("$mod", new[] { denominator, result }); } /// <summary> /// Matches any array with the specified number of elements /// </summary> /// <param name="size">The size.</param> /// <returns></returns> public static DocOP Size(int size) { return (DocOP)new DocOP().Add("$size", size); } /// <summary> /// Check for existence of a field. /// </summary> /// <returns></returns> public static DocOP Exists() { return (DocOP)new DocOP().Add("$exists", true); } /// <summary> /// Check for lack of existence of a field. /// </summary> /// <returns></returns> public static DocOP NotExists() { return (DocOP)new DocOP().Add("$exists", false); } /// <summary> /// Matches values based on their bson type. /// </summary> /// <param name="bsonType">Type of the bson.</param> /// <returns></returns> public static DocOP Type(BsonType bsonType) { return (DocOP)new DocOP().Add("$type", (int)bsonType); } /// <summary> /// Sends the Javascript expressiosn to the server. /// </summary> /// <param name="javascript">The javascript.</param> /// <returns></returns> public static DocOP Where(string javascript) { if(javascript == null) throw new ArgumentNullException("javascript"); return (DocOP)new DocOP().Add("$where", new Code(javascript)); } /// <summary> /// Implements the operator &. This is used for conjunctions. /// </summary> /// <param name="op1">The op1.</param> /// <param name="op2">The op2.</param> /// <returns>The result of the operator.</returns> public static DocOP operator &(DocOP op1, DocOP op2) { return (DocOP)new DocOP().Merge(op1).Merge(op2); } /// <summary> /// Implements the operator !. This is used for the meta operator $not. /// </summary> /// <param name="DocOP">The DocOP.</param> /// <returns>The result of the operator.</returns> public static DocOP operator !(DocOP DocOP) { return (DocOP)new DocOP().Add("$not", DocOP); } public static DocOP or(Document op1, Document op2) { var query = new DocOP { {"$or", new Document[] { op1,op2} } }; return query; } public static DocOP and(Document op1, Document op2) { var query = new DocOP { {"$and", new Document[] { op1,op2} } }; return query; } //var query = new Document //{ // {"$or", new Document[] { new Document("Age", 21), new Document("Age", 35) } } //}; }
4.表继承类
public class LogOper : MongoBasicOper { public LogOper() { m_TableName = "T_LOG"; } public string Add(string Catalog, string Title,string By) { MongoDB.Document doc = new MongoDB.Document(); doc[DColName.Catalog] = Catalog; doc[DColName.Title] = Title; doc[DColName.By] = By; doc[DColName.Time] = DateTime.Now; return Insert(doc); } }
public class LOG
{
private static LogOper log = new LogOper();
public static void Add(string Catalog, string Title,string By)
{
log.Add(Catalog, Title,By);
}
}
5.使用
LOG.Add(LogEnum.系统管理.ToString(), err, string.Empty);