using Contracts.BindingModels; using Contracts.SearchModel; using Contracts.Storage; using Contracts.ViewModels; using MongoDB.Bson; using MongoDB.Driver; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MongoDB { public class PlaceStorage : IPlaceStorage { public MongoClient contex; public PlaceStorage() { contex = MongoDateBase.getInstance().client; } public PlaceVM? Delete(PlaceBM model) { IMongoDatabase db = contex.GetDatabase("logistic"); var collection = db.GetCollection("Place"); var res = collection.FindOneAndDelete(new BsonDocument("name", model.Title)); if (res == null) return null; return new PlaceVM { Title = res["name"].ToString(), }; } public PlaceVM? GetElement(PlaceSM model) { IMongoDatabase db = contex.GetDatabase("logistic"); var collection = db.GetCollection("Place"); BsonDocument place = collection.Find(new BsonDocument("name", model.Title)).FirstOrDefault(); if (place == null) return null; return new PlaceVM { Title = place["name"].ToString(), }; } public List GetFilteredList(PlaceSM model) { IMongoDatabase db = contex.GetDatabase("logistic"); var collection = db.GetCollection("Place"); List statuses = collection.Find(new BsonDocument { { "$regex", $"^.{model.Title}.$" } }).ToList(); List res = new List(); foreach (var status in statuses) { res.Add(new PlaceVM { Title = status["name"].ToString(), }); } return res; } public List GetFullList() { IMongoDatabase db = contex.GetDatabase("logistic"); var collection = db.GetCollection("Place"); List statuses = collection.Find(new BsonDocument()).ToList(); List res = new List(); foreach (var status in statuses) { res.Add(new PlaceVM { Title = status["name"].ToString(), }); } return res; } public PlaceVM? Insert(PlaceBM model) { IMongoDatabase db = contex.GetDatabase("logistic"); var collection = db.GetCollection("Place"); BsonDocument status = new BsonDocument { { "name", model.Title } }; collection.InsertOne(status); return new PlaceVM { Title = model.Title}; } public PlaceVM? Update(PlaceBM model) { IMongoDatabase db = contex.GetDatabase("logistic"); var collection = db.GetCollection("Place"); var result = collection.UpdateOneAsync(new BsonDocument("name", model.oldTitle), new BsonDocument("$set", new BsonDocument("name", model.Title))); if (result == null) return null; return new PlaceVM { Title = model.Title, }; } } }