using LocationsApi.Models; using MongoDB.Bson; using MongoDB.Driver; namespace LocationsApi.Services; public class LocationStore { private readonly IMongoCollection _col; public LocationStore(IConfiguration cfg) { var cs = cfg["MongoDB:ConnectionString"] ?? "mongodb://127.0.0.1:27017"; var dbName = cfg["MongoDB:DatabaseName"] ?? "GameDb"; var client = new MongoClient(cs); var db = client.GetDatabase(dbName); var collectionName = "Locations"; EnsureLocationSchema(db, collectionName); _col = db.GetCollection(collectionName); var coordIndex = Builders.IndexKeys .Ascending(l => l.Coord.X) .Ascending(l => l.Coord.Y); var coordIndexOptions = new CreateIndexOptions { Unique = true }; _col.Indexes.CreateOne(new CreateIndexModel(coordIndex, coordIndexOptions)); } private static void EnsureLocationSchema(IMongoDatabase db, string collectionName) { var validator = new BsonDocument { { "$jsonSchema", new BsonDocument { { "bsonType", "object" }, { "required", new BsonArray { "name", "coord", "createdUtc" } }, { "properties", new BsonDocument { { "name", new BsonDocument { { "bsonType", "string" } } }, { "coord", new BsonDocument { { "bsonType", "object" }, { "required", new BsonArray { "x", "y" } }, { "properties", new BsonDocument { { "x", new BsonDocument { { "bsonType", "int" } } }, { "y", new BsonDocument { { "bsonType", "int" } } } } } } }, { "createdUtc", new BsonDocument { { "bsonType", "date" } } } } } } } }; var options = new CreateCollectionOptions { Validator = new BsonDocumentFilterDefinition(validator), ValidationAction = DocumentValidationAction.Error }; var collections = db.ListCollectionNames().ToList(); if (!collections.Contains(collectionName)) { db.CreateCollection(collectionName, options); return; } var command = new BsonDocument { { "collMod", collectionName }, { "validator", validator }, { "validationAction", "error" } }; db.RunCommand(command); } public Task CreateAsync(Location location) => _col.InsertOneAsync(location); public Task> GetAllAsync() => _col.Find(Builders.Filter.Empty).ToListAsync(); public async Task DeleteAsync(string id) { var filter = Builders.Filter.Eq(l => l.Id, id); var result = await _col.DeleteOneAsync(filter); return result.DeletedCount > 0; } public async Task UpdateNameAsync(string id, string name) { var filter = Builders.Filter.Eq(l => l.Id, id); var update = Builders.Update.Set(l => l.Name, name); var result = await _col.UpdateOneAsync(filter, update); return result.ModifiedCount > 0; } }