Skip to content

Instantly share code, notes, and snippets.

@AleksaDjordjic
Last active August 9, 2021 20:34
Show Gist options
  • Save AleksaDjordjic/72f0f446d4d6e9edefcd8b1f01670b73 to your computer and use it in GitHub Desktop.
Save AleksaDjordjic/72f0f446d4d6e9edefcd8b1f01670b73 to your computer and use it in GitHub Desktop.
Bit more advanced version of perviously uploaded MogoDB C# client for basic CRUD operations and Authorization
using MongoDB.Bson;
using MongoDB.Driver;
using Newtonsoft.Json;
using System.Collections.Generic;
using MongoDB.Bson.Serialization.Attributes;
namespace MongoDBClient
{
public abstract class MongoObject
{
[BsonId]
[JsonConverter(typeof(ObjectIdConverter))]
public ObjectId ID { get; set; }
}
public class Mongo
{
private static string PercentEncode(string input)
{
return input
.Replace(":", "%3A")
.Replace("/", "%2F")
.Replace("?", "%3F")
.Replace("#", "%23")
.Replace("[", "%5B")
.Replace("]", "%5D")
.Replace("@", "%40");
}
protected IMongoDatabase database;
public Mongo(string database)
{
var client = new MongoClient();
this.database = client.GetDatabase(database);
}
public Mongo(string database, string host) : this(database, host, 27017) { }
public Mongo(string database, string host, ushort port)
{
var client = new MongoClient($"mongodb://{host}:{port}");
this.database = client.GetDatabase(database);
}
public Mongo(string database, string host, string username, string password) : this(database, host, 27017, username, password) { }
public Mongo(string database, string host, ushort port, string username, string password)
{
var client = new MongoClient($"mongodb://{PercentEncode(username)}:{PercentEncode(password)}@{host}:{port}/?authSource=admin");
this.database = client.GetDatabase(database);
}
public ObjectId InsertObject(MongoObject obj) => InsertObject(obj.GetType().Name, obj);
public ObjectId InsertObject(string collectionName, MongoObject obj)
{
var collection = database.GetCollection<MongoObject>(collectionName);
collection.InsertOne(obj);
return obj.ID;
}
public List<T> LoadObjects<T>() where T : MongoObject => LoadObjects<T>(typeof(T).Name);
public List<T> LoadObjects<T>(string collectionName) where T : MongoObject
{
var collection = database.GetCollection<T>(collectionName);
return collection.Find(new BsonDocument()).ToList();
}
public List<T> LoadLastAmountObjects<T>(int amount) where T : MongoObject => LoadLastAmountObjects<T>(typeof(T).Name, amount);
public List<T> LoadLastAmountObjects<T>(string collectionName, int amount) where T : MongoObject
{
var collection = database.GetCollection<T>(collectionName);
return collection.Find(new BsonDocument()).Limit(amount).ToList();
}
public bool LoadObjectById<T>(string id, out T result) where T : MongoObject => LoadObjectById(new ObjectId(id), out result);
public bool LoadObjectById<T>(ObjectId id, out T result) where T : MongoObject => LoadObjectById(typeof(T).Name, id, out result);
public bool LoadObjectById<T>(string collectionName, string id, out T result) where T : MongoObject => LoadObjectById(collectionName, new ObjectId(id), out result);
public bool LoadObjectById<T>(string collectionName, ObjectId id, out T result) where T : MongoObject
{
var collection = database.GetCollection<T>(collectionName);
var filter = Builders<T>.Filter.Eq("ID", id);
result = collection.Find(filter).FirstOrDefault();
return result != null;
}
public bool LoadObjectByProperty<T>(string property, object value, out T result) where T : MongoObject => LoadObjectByProperty(typeof(T).Name, property, value, out result);
public bool LoadObjectByProperty<T>(string collectionName, string property, object value, out T result) where T : MongoObject
{
var collection = database.GetCollection<T>(collectionName);
var filter = Builders<T>.Filter.Eq(property, value);
result = collection.Find(filter).FirstOrDefault();
return result != null;
}
public List<T> LoadObjectsByProperty<T>(string property, object value) where T : MongoObject => LoadObjectsByProperty<T>(typeof(T).Name, property, value);
public List<T> LoadObjectsByProperty<T>(string collectionName, string property, object value) where T : MongoObject
{
var collection = database.GetCollection<T>(collectionName);
var filter = Builders<T>.Filter.Eq(property, value);
return collection.Find(filter).ToList();
}
public List<T> LoadObjectsByFilter<T>(FilterDefinition<T> filter) where T : MongoObject => LoadObjectsByFilter(typeof(T).Name, filter);
public List<T> LoadObjectsByFilter<T>(string collectionName, FilterDefinition<T> filter) where T : MongoObject
{
var collection = database.GetCollection<T>(collectionName);
return collection.Find(filter).ToList();
}
public bool LoadObjectByFilter<T>(FilterDefinition<T> filter, out T result) where T : MongoObject => LoadObjectByFilter(typeof(T).Name, filter, out result);
public bool LoadObjectByFilter<T>(string collectionName, FilterDefinition<T> filter, out T result) where T : MongoObject
{
var collection = database.GetCollection<T>(collectionName);
result = collection.Find(filter).FirstOrDefault();
return result != null;
}
public bool UpsertObject(MongoObject obj) => UpsertObject(obj.GetType().Name, obj);
public bool UpsertObject(string collectionName, MongoObject obj)
{
var collection = database.GetCollection<MongoObject>(collectionName);
return collection.ReplaceOne(
new BsonDocument("_id", obj.ID), obj, new ReplaceOptions { IsUpsert = true })
.IsAcknowledged;
}
public bool UpsertObjectById(string id, MongoObject obj) => UpsertObjectById(obj.GetType().Name, new ObjectId(id), obj);
public bool UpsertObjectById(ObjectId id, MongoObject obj) => UpsertObjectById(obj.GetType().Name, id, obj);
public bool UpsertObjectById(string collectionName, string id, MongoObject obj) => UpsertObjectById(collectionName, new ObjectId(id), obj);
public bool UpsertObjectById(string collectionName, ObjectId id, MongoObject obj)
{
var collection = database.GetCollection<MongoObject>(collectionName);
obj.ID = id;
return collection.ReplaceOne(
new BsonDocument("_id", id), obj, new ReplaceOptions { IsUpsert = true })
.IsAcknowledged;
}
public T AtomicIncrementObjectPropertyById<T>(string id, string property, long incrementAmount) where T : MongoObject => AtomicIncrementObjectPropertyById<T>(typeof(T).Name, id, property, incrementAmount);
public T AtomicIncrementObjectPropertyById<T>(ObjectId id, string property, long incrementAmount) where T : MongoObject => AtomicIncrementObjectPropertyById<T>(typeof(T).Name, id, property, incrementAmount);
public T AtomicIncrementObjectPropertyById<T>(string collectionName, string id, string property, long incrementAmount) where T : MongoObject => AtomicIncrementObjectPropertyById<T>(collectionName, new ObjectId(id), property, incrementAmount);
public T AtomicIncrementObjectPropertyById<T>(string collectionName, ObjectId id, string property, long incrementAmount) where T : MongoObject
{
var collection = database.GetCollection<T>(collectionName);
var options = new FindOneAndUpdateOptions<T>() { ReturnDocument = ReturnDocument.After };
var update = Builders<T>.Update.Inc(property, incrementAmount);
return collection.FindOneAndUpdate(new BsonDocument("_id", id), update, options);
}
public T AtomicSetObjectPropertyById<T>(string id, string property, object value) where T : MongoObject => AtomicSetObjectPropertyById<T>(typeof(T).Name, id, property, value);
public T AtomicSetObjectPropertyById<T>(ObjectId id, string property, object value) where T : MongoObject => AtomicSetObjectPropertyById<T>(typeof(T).Name, id, property, value);
public T AtomicSetObjectPropertyById<T>(string collectionName, string id, string property, object value) where T : MongoObject => AtomicSetObjectPropertyById<T>(collectionName, new ObjectId(id), property, value);
public T AtomicSetObjectPropertyById<T>(string collectionName, ObjectId id, string property, object value) where T : MongoObject
{
var collection = database.GetCollection<T>(collectionName);
var options = new FindOneAndUpdateOptions<T>() { ReturnDocument = ReturnDocument.After };
var update = Builders<T>.Update.Set(property, value);
return collection.FindOneAndUpdate(new BsonDocument("_id", id), update, options);
}
public long CountCollection<T>() where T : MongoObject => CountCollection(typeof(T).Name);
public long CountCollection(string colletionName)
{
var collection = database.GetCollection<MongoObject>(colletionName);
return collection.CountDocuments(new BsonDocument());
}
public long CountCollectionByProperty<T>(string property, object value) where T : MongoObject => CountCollectionByProperty<T>(typeof(T).Name, property, value);
public long CountCollectionByProperty<T>(string collectionName, string property, object value) where T : MongoObject
{
var collection = database.GetCollection<T>(collectionName);
var filter = Builders<T>.Filter.Eq(property, value);
return collection.CountDocuments(filter);
}
public long CountCollectionByFilter<T>(FilterDefinition<T> filter) where T : MongoObject => CountCollectionByFilter(typeof(T).Name, filter);
public long CountCollectionByFilter<T>(string collectionName, FilterDefinition<T> filter) where T : MongoObject
{
var collection = database.GetCollection<T>(collectionName);
return collection.CountDocuments(filter);
}
public bool DeleteObject<T>(T obj) where T : MongoObject => DeleteObject<T>(typeof(T).Name, (obj as MongoObject).ID);
public bool DeleteObject<T>(string id) where T : MongoObject => DeleteObject<T>(typeof(T).Name, new ObjectId(id));
public bool DeleteObject<T>(ObjectId id) where T : MongoObject => DeleteObject<T>(typeof(T).Name, id);
public bool DeleteObject<T>(string collectionName, string id) where T : MongoObject => DeleteObject<T>(collectionName, new ObjectId(id));
public bool DeleteObject<T>(string collectionName, ObjectId id) where T : MongoObject
{
var collection = database.GetCollection<T>(collectionName);
var filter = Builders<T>.Filter.Eq("ID", id);
return collection.DeleteOne(filter).IsAcknowledged;
}
public bool DeleteObjectByProperty<T>(string property, object value) where T : MongoObject => DeleteObjectByProperty<T>(typeof(T).Name, property, value);
public bool DeleteObjectByProperty<T>(string collectionName, string property, object value) where T : MongoObject
{
var collection = database.GetCollection<T>(collectionName);
var filter = Builders<T>.Filter.Eq(property, value);
return collection.DeleteOne(filter).IsAcknowledged;
}
public bool DeleteObjectByFilter<T>(FilterDefinition<T> filter) where T : MongoObject => DeleteObjectByFilter(typeof(T).Name, filter);
public bool DeleteObjectByFilter<T>(string collectionName, FilterDefinition<T> filter) where T : MongoObject
{
var collection = database.GetCollection<T>(collectionName);
return collection.DeleteOne(filter).IsAcknowledged;
}
public bool CollectionExists<T>() where T : MongoObject => CollectionExists<T>(typeof(T).Name);
public bool CollectionExists<T>(string collectionName) where T : MongoObject
{
var collection = database.GetCollection<T>(collectionName);
return collection != null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment