#if DOTNET || UNITY_EDITOR || UNITY_STANDALONE_WIN || UNITY_STANDALONE_LINUX || UNITY_STANDALONE_OSX using System; using System.Collections.Generic; using System.Linq; using MongoDB.Driver; namespace ET.Server { [EnableClass] public sealed class MongoDBComponent : IDBComponent { private readonly IMongoDatabase database; public MongoDBComponent(string connectionString, string dbName) { if (string.IsNullOrWhiteSpace(connectionString)) { throw new ArgumentException("Mongo connection string is empty.", nameof(connectionString)); } if (string.IsNullOrWhiteSpace(dbName)) { throw new ArgumentException("Mongo DB name is empty.", nameof(dbName)); } MongoClient client = new(connectionString); this.database = client.GetDatabase(dbName); } public async ETTask Save(long entityId, T entity) where T : class { DbEntityRecord record = new() { Id = entityId, Payload = MongoHelper.Serialize(entity) }; IMongoCollection collection = this.GetCollection(); await collection.ReplaceOneAsync(x => x.Id == entityId, record, new ReplaceOptions { IsUpsert = true }); } public async ETTask QueryByEntityId(long entityId) where T : class { IMongoCollection collection = this.GetCollection(); DbEntityRecord record = await collection.Find(x => x.Id == entityId).FirstOrDefaultAsync(); return record == null ? null : MongoHelper.Deserialize(record.Payload); } public async ETTask> Query(Func predicate = null) where T : class { IMongoCollection collection = this.GetCollection(); List records = await collection.Find(Builders.Filter.Empty).ToListAsync(); IEnumerable entities = records.Select(x => MongoHelper.Deserialize(x.Payload)); if (predicate != null) { entities = entities.Where(predicate); } return entities.ToList(); } public ETTask Update(long entityId, T entity) where T : class { return this.Save(entityId, entity); } public async ETTask Delete(long entityId) where T : class { IMongoCollection collection = this.GetCollection(); await collection.DeleteOneAsync(x => x.Id == entityId); } private IMongoCollection GetCollection() where T : class { string collectionName = typeof(T).Name; return this.database.GetCollection(collectionName); } } } #endif