//Please note this class uses lazy instantiation. If more clearification is needed, send me a discord message and //ill change the code accordling to make it abit more readable. /// <summary> /// Will insert the calling object into the database into the relevant /// </summary> public static bool InsertDocument(this CRUDAble obj, string databaseName = "FlourishDB") { //the following method will do the following tasks in order: // 1. establishes a connection to the database with the databasename specified, if none specified then it will use its // predefined database name of 'FlourishDB'. //2. Once established, it will obtain the collection that is of the same type of the object that initiated the method. //3. Once collection is obtained, it then inserts the object that initiated the method into the database in the correct Collection and returns a True bool. // ~ if the object already exists in the document then it will return false to the system that called the method. IMongoCollection <CRUDAble> collection = new DatabaseConnection().DatabaseConnect(databaseName).GetCollection <CRUDAble>(obj.GetType().Name); // ~ Consists of Point 1 if (collection.AsQueryable().Where(p => p.HashCode == obj.HashCode).LongCount() > 0) // used to check if the current object already exists { return(false); // returns a false statement if it does } collection.InsertOne((CRUDAble)obj); // this will insert the object return(true); // everything completed successfully }
public static void Delete(this CRUDAble obj, string databaseName = "FlourishDB") { var selectedCollection = new DatabaseConnection().DatabaseConnect(databaseName).GetCollection <CRUDAble>(obj.GetType().Name); BsonDocument filter = new BsonDocument().Add("HashCode", obj.HashCode); selectedCollection.DeleteOne(filter); }
/// <summary> /// This will search for a collection of objects based on a user specified list of criteria, it then returns a of List<CRUDAble> objects which the user can then manipulate /// Please note that this method will only do "Equals to" comparison /// </summary> public static List <CRUDAble> SearchDocument(this CRUDAble searchObject, Dictionary <string, object> queryDictionary, string databaseName = "FlourishDB") { // the below statement just obtains the relevent document collection associated with the search var selectedCollection = new DatabaseConnection().DatabaseConnect(databaseName).GetCollection <CRUDAble>(searchObject.GetType().Name); BsonDocument filter = new BsonDocument(); // we create a blank filter foreach (string item in queryDictionary.Keys) // we now iterate through our dictionary looking for all key and value types { if (queryDictionary[item] != null) // if the value type is not null for a key, then we add it to our filter list { filter.Add(item, queryDictionary[item].ToString()); } } return(selectedCollection.Find(filter).ToList()); // this will use the filter to return a list of only documents that fit that specific filter }