
本文共 14318 字,大约阅读时间需要 47 分钟。
��������������������������� MongoDb���������������������������������������������MongoDb������������������������������������MongoDb������������������������2.4���������������������������������������MongoDb Helper���������������������MongoDb������������������������������������������MongoDb���������������MongoDb������C#���������������������MongoDbCsharpHelper������CRUD������������������������������
using MongoDB;using MongoDB.Bson;using MongoDB.Driver;using System;using System.Collections;using System.Collections.Generic;using System.Linq;using System.Linq.Expressions;using System.Reflection;using System.Threading;using System.Web;namespace Zuowj.Utils{ ////// MongoDbCsharpHelper:MongoDb������C#��������������������� /// Author:Zuowenjun /// Date:2017/11/16 /// public class MongoDbCsharpHelper { private readonly string connectionString = null; private readonly string databaseName = null; private MongoDB.Driver.IMongoDatabase database = null; private readonly bool autoCreateDb = false; private readonly bool autoCreateCollection = false; static MongoDbCsharpHelper() { BsonDefaults.GuidRepresentation = GuidRepresentation.Standard; } public MongoDbCsharpHelper(string mongoConnStr, string dbName, bool autoCreateDb = false, bool autoCreateCollection = false) { this.connectionString = mongoConnStr; this.databaseName = dbName; this.autoCreateDb = autoCreateDb; this.autoCreateCollection = autoCreateCollection; } #region ������������ private MongoClient CreateMongoClient() { return new MongoClient(connectionString); } private MongoDB.Driver.IMongoDatabase GetMongoDatabase() { if (database == null) { var client = CreateMongoClient(); if (!DatabaseExists(client, databaseName) && !autoCreateDb) { throw new KeyNotFoundException("���MongoDB������������������" + databaseName); } database = CreateMongoClient().GetDatabase(databaseName); } return database; } private bool DatabaseExists(MongoClient client, string dbName) { try { var dbNames = client.ListDatabases().ToList().Select(db => db.GetValue("name").AsString); return dbNames.Contains(dbName); } catch //������������������������������������������DB������������������������true { return true; } } private bool CollectionExists(IMongoDatabase database, string collectionName) { var options = new ListCollectionsOptions { Filter = Builders.Filter.Eq("name", collectionName) }; return database.ListCollections(options).ToEnumerable().Any(); } private MongoDB.Driver.IMongoCollection GetMongoCollection (string name, MongoCollectionSettings settings = null) { var mongoDatabase = GetMongoDatabase(); if (!CollectionExists(mongoDatabase, name) && !autoCreateCollection) { throw new KeyNotFoundException("���Collection������������������" + name); } return mongoDatabase.GetCollection (name, settings); } private List > BuildUpdateDefinition (object doc, string parent) { var updateList = new List >(); foreach (var property in typeof(TDoc).GetProperties(BindingFlags.Instance | BindingFlags.Public)) { var key = parent == null ? property.Name : string.Format("{0}.{1}", parent, property.Name); //��������������������� if ((property.PropertyType.IsClass || property.PropertyType.IsInterface) && property.PropertyType != typeof(string) && property.GetValue(doc) != null) { if (typeof(IList).IsAssignableFrom(property.PropertyType)) { #region ������������ int i = 0; var subObj = property.GetValue(doc); foreach (var item in subObj as IList) { if (item.GetType().IsClass || item.GetType().IsInterface) { updateList.AddRange(BuildUpdateDefinition (doc, string.Format("{0}.{1}", key, i))); } else { updateList.Add(Builders .Update.Set(string.Format("{0}.{1}", key, i), item)); } i++; } #endregion } else { #region ������������ //������������������������������������������������������ var subObj = property.GetValue(doc); foreach (var sub in property.PropertyType.GetProperties(BindingFlags.Instance | BindingFlags.Public)) { updateList.Add(Builders .Update.Set(string.Format("{0}.{1}", key, sub.Name), sub.GetValue(subObj))); } #endregion } } else //������������ { updateList.Add(Builders .Update.Set(key, property.GetValue(doc))); } } return updateList; } private void CreateIndex (IMongoCollection col, string[] indexFields, CreateIndexOptions options = null) { if (indexFields == null) { return; } var indexKeys = Builders .IndexKeys; IndexKeysDefinition keys = null; if (indexFields.Length > 0) { keys = indexKeys.Descending(indexFields[0]); } for (var i = 1; i < indexFields.Length; i++) { var strIndex = indexFields[i]; keys = keys.Descending(strIndex); } if (keys != null) { col.Indexes.CreateOne(keys, options); } } #endregion public void CreateCollectionIndex (string collectionName, string[] indexFields, CreateIndexOptions options = null) { CreateIndex(GetMongoCollection (collectionName), indexFields, options); } public void CreateCollection (string[] indexFields = null, CreateIndexOptions options = null) { string collectionName = typeof(TDoc).Name; CreateCollection (collectionName, indexFields, options); } public void CreateCollection (string collectionName, string[] indexFields = null, CreateIndexOptions options = null) { var mongoDatabase = GetMongoDatabase(); mongoDatabase.CreateCollection(collectionName); CreateIndex(GetMongoCollection (collectionName), indexFields, options); } public List Find (Expression > filter, FindOptions options = null) { string collectionName = typeof(TDoc).Name; return Find (collectionName, filter, options); } public List Find (string collectionName, Expression > filter, FindOptions options = null) { var colleciton = GetMongoCollection (collectionName); return colleciton.Find(filter, options).ToList(); } public List FindByPage (Expression > filter, Expression > keySelector, int pageIndex, int pageSize, out int rsCount) { string collectionName = typeof(TDoc).Name; return FindByPage (collectionName, filter, keySelector, pageIndex, pageSize, out rsCount); } public List FindByPage (string collectionName, Expression > filter, Expression > keySelector, int pageIndex, int pageSize, out int rsCount) { var colleciton = GetMongoCollection (collectionName); rsCount = colleciton.AsQueryable().Where(filter).Count(); int pageCount = rsCount / pageSize + ((rsCount % pageSize) > 0 ? 1 : 0); if (pageIndex > pageCount) pageIndex = pageCount; if (pageIndex <= 0) pageIndex = 1; return colleciton.AsQueryable(new AggregateOptions { AllowDiskUse = true }).Where(filter).OrderByDescending(keySelector).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(); } public void Insert (TDoc doc, InsertOneOptions options = null) { string collectionName = typeof(TDoc).Name; Insert (collectionName, doc, options); } public void Insert (string collectionName, TDoc doc, InsertOneOptions options = null) { var colleciton = GetMongoCollection (collectionName); colleciton.InsertOne(doc, options); } public void InsertMany (IEnumerable docs, InsertManyOptions options = null) { string collectionName = typeof(TDoc).Name; InsertMany (collectionName, docs, options); } public void InsertMany (string collectionName, IEnumerable docs, InsertManyOptions options = null) { var colleciton = GetMongoCollection (collectionName); colleciton.InsertMany(docs, options); } public void Update (TDoc doc, Expression > filter, UpdateOptions options = null) { string collectionName = typeof(TDoc).Name; var colleciton = GetMongoCollection (collectionName); List > updateList = BuildUpdateDefinition (doc, null); colleciton.UpdateOne(filter, Builders .Update.Combine(updateList), options); } public void Update (string collectionName, TDoc doc, Expression > filter, UpdateOptions options = null) { var colleciton = GetMongoCollection (collectionName); List > updateList = BuildUpdateDefinition (doc, null); colleciton.UpdateOne(filter, Builders .Update.Combine(updateList), options); } public void Update (TDoc doc, Expression > filter, UpdateDefinition updateFields, UpdateOptions options = null) { string collectionName = typeof(TDoc).Name; Update (collectionName, doc, filter, updateFields, options); } public void Update (string collectionName, TDoc doc, Expression > filter, UpdateDefinition updateFields, UpdateOptions options = null) { var colleciton = GetMongoCollection (collectionName); colleciton.UpdateOne(filter, updateFields, options); } public void UpdateMany (TDoc doc, Expression > filter, UpdateOptions options = null) { string collectionName = typeof(TDoc).Name; UpdateMany (collectionName, doc, filter, options); } public void UpdateMany (string collectionName, TDoc doc, Expression > filter, UpdateOptions options = null) { var colleciton = GetMongoCollection (collectionName); List > updateList = BuildUpdateDefinition (doc, null); colleciton.UpdateMany(filter, Builders .Update.Combine(updateList), options); } public void Delete (Expression > filter, DeleteOptions options = null) { string collectionName = typeof(TDoc).Name; Delete (collectionName, filter, options); } public void Delete (string collectionName, Expression > filter, DeleteOptions options = null) { var colleciton = GetMongoCollection (collectionName); colleciton.DeleteOne(filter, options); } public void DeleteMany (Expression > filter, DeleteOptions options = null) { string collectionName = typeof(TDoc).Name; DeleteMany (collectionName, filter, options); } public void DeleteMany (string collectionName, Expression > filter, DeleteOptions options = null) { var colleciton = GetMongoCollection (collectionName); colleciton.DeleteMany(filter, options); } public void ClearCollection (string collectionName) { var colleciton = GetMongoCollection (collectionName); var inddexs = colleciton.Indexes.List(); List > docIndexs = new List >(); while (inddexs.MoveNext()) { docIndexs.Add(inddexs.Current); } var mongoDatabase = GetMongoDatabase(); mongoDatabase.DropCollection(collectionName); if (!CollectionExists(mongoDatabase, collectionName)) { CreateCollection (collectionName); } if (docIndexs.Count > 0) { colleciton = mongoDatabase.GetCollection (collectionName); foreach (var index in docIndexs) { foreach (IndexKeysDefinition indexItem in index) { try { colleciton.Indexes.CreateOne(indexItem); } catch { } } } } } }}
���������������������������������������������������������
1.������MongoClient.GetDatabase ������DB���MongoClient.GetCollection<TDoc> ������������������������������������������ ������������������������������������������DB���������Collection���������������������������������������������������������������������DB���������Collection������������������������������������DB���Collection������������������������������������������MongoDbCsharpHelper���������������������������������������������DatabaseExists���������DB������������������������������������������������DB���������������������������������������������������������true������CollectionExists���������Collection������������������
2.������CRUD������������������������������������������������������������������Collection������������������������������Collection���������������������������������������������������������������Collection���������������������������������������Collection���������TDoc���������������������������collectionName������������������
3.���������������������������Collection������������������������������������������������������exception: Sort exceeded memory limit of 104857600 bytes, but did not opt in to external sorting. Aborting operation. Pass allowDiskUse:true������������������������������������������������������������AggregateOptions��������������� colleciton.AsQueryable(new AggregateOptions { AllowDiskUse = true })
4.ClearCollection������Collection������������������������Collection������������������������������������������colleciton.DeleteMany������������������������������������SQL SERVER ���truncate table������������������������������������������������������������������������������������������DropCollection������������������DropCollection���������������������Collection���������������Collection������������������������������������������������������Drop���Collection������������������������������������������������Collection���������������������������������������������������������������������������������DropCollection ���������CreateCollection���������������������������������������������������������Collection������������������������truncate ���������������������������������������������������������������������������������������������_id������������_id���������������������������������������������������������������colleciton.Indexes.CreateOne������������try catch���������������������������
5.CreateCollection���������������������CreateCollectionIndex������������������������������������������������������������������������������Collection���������������Collection���������������������������shell������������������������������������������������������
���������������������
var mongoDbHelper = new MongoDbCsharpHelper("MongoDbConnectionString", "LogDB"); mongoDbHelper.CreateCollection("SysLog1",new[]{"LogDT"}); mongoDbHelper.Find ("SysLog1", t => t.Level == "Info"); int rsCount=0; mongoDbHelper.FindByPage ("SysLog1",t=>t.Level=="Info",t=>t,1,20,out rsCount); mongoDbHelper.Insert ("SysLog1",new SysLogInfo { LogDT = DateTime.Now, Level = "Info", Msg = "������������" }); mongoDbHelper.Update ("SysLog1",new SysLogInfo { LogDT = DateTime.Now, Level = "Error", Msg = "������������2" },t => t.LogDT==new DateTime(1900,1,1)); mongoDbHelper.Delete (t => t.Level == "Info"); mongoDbHelper.ClearCollection ("SysLog1");
发表评论
最新留言
关于作者
