public AccountEntity Find(string accountName) { try { var collection = Connect(DataAccessConstants.DatabaseName).GetCollection <AccountEntity>(CollectionName); var account = IMongoCollectionExtensions.Find <AccountEntity>(collection, f => f.AccountName.Equals(accountName)).FirstOrDefault(); if (account != null) { return new AccountEntity() { AccountId = account.AccountId, AccountName = account.AccountName, Password = account.Password, AccountType = account.AccountType, IsLoggedIn = account.IsLoggedIn, LastLoginDate = account.LastLoginDate } } ; } catch (Exception e) { throw new KeyNotFoundException($"Account Name not found: {accountName}"); } throw new KeyNotFoundException($"Account Name not found: {accountName}"); }
public async Task AddRecurrentJob(JobDb job) { var collection = _mongoClientProvider.GetCollection <JobMongoModel>(); var update = Builders <JobMongoModel> .Update .Set(x => x.Cron, job.Cron) .Set(x => x.StartAt, job.StartAt); var needsProperties = _jobDbProperties.Where(x => x.Name != nameof(JobMongoModel.Cron) && x.Name != nameof(JobMongoModel.StartAt)); //Если джоб уже существет апдейтем только 2 поля //Если нужно создать, то устанавливаем все остальные поля foreach (var jobDbProperty in needsProperties) { update = update.SetOnInsert(jobDbProperty.Name, jobDbProperty.GetValue(job)); } await IMongoCollectionExtensions.UpdateOneAsync(collection, x => x.JobKey == job.JobKey && (x.Status == JobStatus.Executing || x.Status == JobStatus.Ready), update, new UpdateOptions { IsUpsert = true }); }
public async Task <StaticPagedList <T> > PaginationAsync(int page, int total, SortDefinition <T> sortBy, Expression <Func <T, bool> > query = null) { StaticPagedList <T> staticPagedList; CancellationToken cancellationToken; long num = (long)0; if (query != null) { IMongoCollection <T> collection = this.Collection; FilterDefinition <T> filterDefinition = query; cancellationToken = new CancellationToken(); num = await collection.CountAsync(filterDefinition, null, cancellationToken); IFindFluent <T, T> findFluent = IMongoCollectionExtensions.Find <T>(this.Collection, query, null).Skip(new int?((page - 1) * total)).Limit(new int?(total)).Sort(sortBy); cancellationToken = new CancellationToken(); List <T> listAsync = await IAsyncCursorSourceExtensions.ToListAsync <T>(findFluent, cancellationToken); staticPagedList = new StaticPagedList <T>(listAsync, page, total, (int)num); } else { IMongoCollection <T> mongoCollection = this.Collection; FilterDefinition <T> bsonDocument = new BsonDocument(); cancellationToken = new CancellationToken(); num = await mongoCollection.CountAsync(bsonDocument, null, cancellationToken); IFindFluent <T, T> findFluent1 = IMongoCollectionExtensions.Find <T>(this.Collection, new BsonDocument(), null).Skip(new int?((page - 1) * total)).Limit(new int?(total)).Sort(sortBy); cancellationToken = new CancellationToken(); List <T> ts = await IAsyncCursorSourceExtensions.ToListAsync <T>(findFluent1, cancellationToken); staticPagedList = new StaticPagedList <T>(ts, page, total, (int)num); } return(staticPagedList); }
public CustomerEntity Find(string customerName) { try { var collection = Connect(DataAccessConstants.DatabaseName) .GetCollection <CustomerEntity>(CollectionName); var customer = IMongoCollectionExtensions .Find <CustomerEntity>(collection, f => f.CustomerName.Equals(customerName)).FirstOrDefault(); if (customer != null) { return(new CustomerEntity() { CustomerId = customer.CustomerId, CustomerName = customer.CustomerName, DateOfBirth = customer.DateOfBirth, Address = customer.Address, PhoneNumber = customer.PhoneNumber, SchemesCards = customer.SchemesCards }); } } catch (Exception e) { throw new KeyNotFoundException($"Customer Name not found: {customerName}"); } throw new KeyNotFoundException($"Customer Name not found: {customerName}"); }
public async Task <StaticPagedList <T> > PaginationAsync <TKey>(int pageIndex, int pageSize, Expression <Func <T, TKey> > orderBy, bool isOrderByAsc = true, Expression <Func <T, bool> > where = null) { long num; long num1 = (long)0; IMongoQueryable <T> mongoQueryable = IMongoCollectionExtensions.AsQueryable <T>(this.Collection, new AggregateOptions() { AllowDiskUse = true }); num = (where != null ? await this.CountAsync(where) : await this.CountAsync()); num1 = num; if (where != null) { mongoQueryable = MongoQueryable.Where <T>(mongoQueryable, where); } if (isOrderByAsc) { mongoQueryable = MongoQueryable.Take <T>(MongoQueryable.Skip <T>(MongoQueryable.OrderBy <T, TKey>(mongoQueryable, orderBy), (pageIndex - 1) * pageSize), pageSize); } else { mongoQueryable = MongoQueryable.Take <T>(MongoQueryable.Skip <T>(MongoQueryable.OrderByDescending <T, TKey>(mongoQueryable, orderBy), (pageIndex - 1) * pageSize), pageSize); } StaticPagedList <T> staticPagedList = new StaticPagedList <T>(mongoQueryable.ToList <T>(), pageIndex, pageSize, (int)num1); return(staticPagedList); }
public PrescriptionEntity Find(string name) { try { var collection = Connect(DataAccessConstants.DatabaseName).GetCollection <PrescriptionEntity>(CollectionName); var prescription = IMongoCollectionExtensions.Find <PrescriptionEntity>(collection, f => f.CustomerName.Equals(name) || f.GpName.Equals(name)).FirstOrDefault(); if (prescription != null) { return new PrescriptionEntity() { PrescriptionId = prescription.PrescriptionId, CustomerName = prescription.CustomerName, GpName = prescription.GpName, Products = prescription.Products } } ; } catch (Exception e) { throw new KeyNotFoundException($"Customer or GP name not found: {name}"); } throw new KeyNotFoundException($"Customer or GP name not found: {name}"); }
public async Task <T> FindAsync <TKey>(TKey id, string name = "_id") { FilterDefinition <T> filterDefinition = Builders <T> .Filter.Eq <TKey>(name, id); IFindFluent <T, T> findFluent = IMongoCollectionExtensions.Find <T>(this.Collection, filterDefinition, null); return(await IFindFluentExtensions.FirstOrDefaultAsync <T, T>(findFluent, new CancellationToken())); }
public List <TField> Distinct <TField>(Expression <Func <TEntity, TField> > fieldExp, FilterDefinition <TEntity> filter, ReadPreference readPreference = null) { if (filter == null) { filter = Filter.Empty; } return(IAsyncCursorExtensions.ToList <TField>(IMongoCollectionExtensions.Distinct <TEntity, TField>(GetCollection(readPreference), fieldExp, filter, null))); }
protected IAggregateFluent <TEntity> CreateAggregate(FilterDefinition <TEntity> filter, SortDefinition <TEntity> sort, ReadPreference readPreference = null) { IAggregateFluent <TEntity> fluent = IMongoCollectionExtensions.Aggregate(this.GetCollection(readPreference), null).Match(filter); if (sort != null) { fluent = fluent.Sort(sort); } return(fluent); }
public StaticPagedList <T> Pagination <TKey>(int page, int total, Expression <Func <T, TKey> > orderBy, Expression <Func <T, bool> > where = null) { long count = (long)0; IMongoQueryable <T> model = IMongoCollectionExtensions.AsQueryable <T>(this.Collection); count = (where == null ? this.Count() : this.Count(where)); if (where != null) { model = MongoQueryable.Where <T>(model, where); } model = MongoQueryable.Take <T>(MongoQueryable.Skip <T>(MongoQueryable.OrderBy <T, TKey>(model, orderBy), (page - 1) * total), total); return(new StaticPagedList <T>(model.ToList <T>(), page, total, (int)count)); }
public StaticPagedList <T> Pagination <TKey>(int pageIndex, int pageSize, Expression <Func <T, TKey> > orderBy, bool isOrderByAsc = true, Expression <Func <T, bool> > where = null) { long count = (long)0; IMongoQueryable <T> model = IMongoCollectionExtensions.AsQueryable <T>(this.Collection); count = (where == null ? this.Count() : this.Count(where)); if (where != null) { model = MongoQueryable.Where <T>(model, where); } model = MongoQueryable.Take <T>(MongoQueryable.Skip <T>(isOrderByAsc ? MongoQueryable.OrderBy <T, TKey>(model, orderBy) : MongoQueryable.OrderByDescending <T, TKey>(model, orderBy), (pageIndex - 1) * pageSize), pageSize); return(new StaticPagedList <T>(model.ToList <T>(), pageIndex, pageSize, (int)count)); }
public async Task <StaticPagedList <T> > PaginationAsync(int page, int total, SortDefinition <T> sortBy, FilterDefinition <T> query) { long num = (long)0; IMongoCollection <T> collection = this.Collection; FilterDefinition <T> filterDefinition = query; CancellationToken cancellationToken = new CancellationToken(); num = await collection.CountAsync(filterDefinition, null, cancellationToken); IFindFluent <T, T> findFluent = IMongoCollectionExtensions.Find <T>(this.Collection, query, null).Skip(new int?((page - 1) * total)).Limit(new int?(total)).Sort(sortBy); cancellationToken = new CancellationToken(); List <T> listAsync = await IAsyncCursorSourceExtensions.ToListAsync <T>(findFluent, cancellationToken); return(new StaticPagedList <T>(listAsync, page, total, (int)num)); }
public async Task <StaticPagedList <T> > PaginationAsync <TKey>(int page, int total, Expression <Func <T, TKey> > orderBy, Expression <Func <T, bool> > where = null) { long num; long num1 = (long)0; IMongoQueryable <T> mongoQueryable = IMongoCollectionExtensions.AsQueryable <T>(this.Collection); num = (where != null ? await this.CountAsync(where) : await this.CountAsync()); num1 = num; if (where != null) { mongoQueryable = MongoQueryable.Where <T>(mongoQueryable, where); } mongoQueryable = MongoQueryable.Take <T>(MongoQueryable.Skip <T>(MongoQueryable.OrderBy <T, TKey>(mongoQueryable, orderBy), (page - 1) * total), total); StaticPagedList <T> staticPagedList = new StaticPagedList <T>(mongoQueryable.ToList <T>(), page, total, (int)num1); return(staticPagedList); }
/// <summary>TODO The aa.</summary> public void Aa() { var client = new MongoClient("mongodb://*****:*****@"http://stackoverflow.com/documentation/mongodb-csharp", VisitPageIndex = 4 }, new Pages { Url = @"https://github.com/", VisitPageIndex = 2 } } }; collection.InsertOne(newItem); var result = IMongoCollectionExtensions.AsQueryable(collection).FirstOrDefault(s => s.SiteName == "Example"); var update = Builders <Interactions> .Update.Set(s => s.SiteName, "New Example"); IMongoCollectionExtensions.FindOneAndUpdate(collection, s => s.SiteName == "Example", update); IMongoCollectionExtensions.DeleteOne(collection, s => s.SiteName == "New Example"); /* * from mongo driver * var result = Group(x => x.A, g => new RootView { Property = g.Key, Field = g.First().B }); * result.Projection.Should().Be("{ _id: \"$A\", Field: { \"$first\" : \"$B\" } }" * * var result2 = IAggregateFluentExtensions.Unwind(IMongoCollectionExtensions.Aggregate(collection), e => e.Pages) * .Group<Pages>(p => p.Pages.url, e => new Pages { Url = e.Key, VisitPageIndex = e.Count() }); * * // var resurt = collection.Aggregate<BsonDocument>().Unwind<BsonDocument>(unwind) */ }
public async Task <IEnumerable <T> > AllAsync(FilterDefinition <T> query, SortDefinition <T> sortBy = null) { IEnumerable <T> listAsync; CancellationToken cancellationToken; IFindFluent <T, T> findFluent = IMongoCollectionExtensions.Find <T>(this.Collection, query, null); if (sortBy == null) { IFindFluent <T, T> findFluent1 = findFluent; cancellationToken = new CancellationToken(); listAsync = await IAsyncCursorSourceExtensions.ToListAsync <T>(findFluent1, cancellationToken); } else { IFindFluent <T, T> findFluent2 = findFluent.Sort(sortBy); cancellationToken = new CancellationToken(); listAsync = await IAsyncCursorSourceExtensions.ToListAsync <T>(findFluent2, cancellationToken); } return(listAsync); }
public JsonResult Login([FromBody] LoginModel login) { var aa = this.HttpContext.Request.Body; BaseMessage loginMessage = new BaseMessage(); var userCollection = mongodb.GetMongodbCollection <SessionUsers>("Users"); //MongoDB.Driver.ExpressionFilterDefinition<Users> mongodbQuery = new MongoDB.Driver.ExpressionFilterDefinition<Users>(entity => entity.UserName == login.loginName && entity.Activity == "1"); //var userCursor = userCollection.FindSync<Users>(mongodbQuery); string guid = Guid.NewGuid().ToString(); if (userCollection != null) { var userFluent = IMongoCollectionExtensions.Find <SessionUsers>(userCollection, entity => entity.UserName == login.username && entity.Password == login.password && entity.Activity == "1"); if (userFluent.Count() > 0) { var user = userFluent.First(); SessionUsers sessionUser = user; sessionUser.ExpireTime = DateTime.Now.AddMinutes(20); sessionUser.SessionId = guid; SessionHelper.SessionUser.Add(sessionUser); loginMessage.code = HttpStatus.Success; loginMessage.data = new ExpandoObject(); loginMessage.data.SessionId = guid; loginMessage.data.DspName = sessionUser.UserDspName; loginMessage.data.ImgUrl = HttpContext.Request.Host.Value + new PathString("/UpLoadImg").Value + "/" + sessionUser.ImgUrl; loginMessage.msg = "µÇ½³É¹¦£¡"; } else { log.Error("ÕË»§»òÃÜÂë´íÎó"); loginMessage.msg = "ÕË»§»òÃÜÂë´íÎó£¡"; loginMessage.code = HttpStatus.LoginFailed; ErrorLoginHelper.AddErrorLoginCount(login.username); if (ErrorLoginHelper.GetErrorLoginCount(login.username) >= 10) { log.Info("ײ¿â¹¥»÷" + Common.ErrorLoginHelper.GetUserIp(this.HttpContext)); } } } else { loginMessage.msg = "·þÎñ¶Ë´íÎó£¬ÇëÁªÏµ¹ÜÀíÔ±£¡"; log.Error("·þÎñ¶Ë´íÎó£¬ÇëÁªÏµ¹ÜÀíÔ±£¡"); loginMessage.code = HttpStatus.LoginFailed; } //List<Users> myList = new List<Users>() { new Users() { CreateTime =DateTime.Now,UserId="1",Activity="1"},new Users() { CreateTime=DateTime.Now.AddDays(1),UserId="2",Activity="1",UserType=1} }; //ParameterExpression parameter1 = Expression.Parameter(typeof(Users), "p"); //ConstantExpression constant1 = Expression.Constant(DateTime.Now.AddMinutes(30)); //ConstantExpression constant2 = Expression.Constant(DateTime.Now.AddDays(2)); //MemberExpression member = Expression.PropertyOrField(parameter1, "CreateTime"); //var query1 = Expression.GreaterThan(member, constant1); //var query2 = Expression.LessThan(Expression.PropertyOrField(parameter1, "CreateTime"), constant2); //var query = Expression.And(query1, query2); //var lambda1 = Expression.Lambda<Func<Users, Boolean>>(query, parameter1); //var list = myList.Where(lambda1.Compile()); //return Json(guid); return(Json(loginMessage)); }
public IMongoQueryable <T> Query() { return(IMongoCollectionExtensions.AsQueryable <T>(this.Collection)); }
public async void Test4GetAsync() { var mockClient = new Mock <IMongoClient>(); var mockContext = new Mock <IMongoContext>(); var client = mockClient.Object; var mockCollection = CreateMockCollection(); var collection = mockCollection.Object; var session = new Mock <IClientSessionHandle>().Object; var options = new ChangeStreamOptions(); var cancellationToken = new CancellationTokenSource().Token; Book document = new Book(); document.Author = "asdas"; document.BookName = "sadasd"; document.Id = ObjectId.GenerateNewId().ToString(); collection.InsertOne(document); var bookMock = new Mock <IFindFluent <Book, Book> >(); mockContext.Setup(x => x.GetCollection <Book>("Book")).Returns(mockCollection.Object); BookstoreDatabaseSettings setting = new BookstoreDatabaseSettings(); setting.BooksCollectionName = "Book"; var mockIDBsettings = new Mock <IOptions <BookstoreDatabaseSettings> >(); mockIDBsettings.Setup(x => x.Value).Returns(setting); //mockCollection.Setup(x => x.FindAsync(It.IsAny<ExpressionFilterDefinition<Book>>(), null, cancellationToken)) // .Returns(bookMock.Object); BookService service = new BookService(mockIDBsettings.Object, mockContext.Object); //service.Create(document); var result = await service.GetBooksAsync(); mockContext.Verify(x => x.GetCollection <Book>("Book"), Times.Once); var options1 = new FindOptions <Book>(); // no projection // var filterExpression = (Expression<Func<Book, bool>>)(x => x.BookName == "sadasd"); var filter = It.IsAny <ExpressionFilterDefinition <Book> >(); var filter1 = It.IsAny <FilterDefinition <Book> >(); //var filter2 = It.IsAny<EmptyFilterDefinition<Book>>(); //FindFluent<Book, Book> fluent; // //mockCollection.Verify(x=>x.Find(filterExpression, null), Times.Once); // //var filterDefinition = Builders<Book>.Filter.Eq("BookName", "sadasd"); var filterExpression = (Expression <Func <Book, bool> >)(x => x.BookName == "sadasd"); IMongoCollectionExtensions.FindAsync(collection, session, filterExpression, options1, cancellationToken); mockCollection.Verify(m => m.FindAsync <Book>(session, It.IsAny <ExpressionFilterDefinition <Book> >(), options1, cancellationToken), Times.Once); mockCollection.Verify(m => m.FindAsync <Book>(FilterDefinition <Book> .Empty, null, CancellationToken.None), Times.Once); // // // // // }
public IList <T> All() { return(IMongoCollectionExtensions.AsQueryable <T>(this.Collection).ToList <T>()); }
public IList <T> All <TKey>(Expression <Func <T, TKey> > orderBy, Expression <Func <T, bool> > where) { return(MongoQueryable.OrderBy <T, TKey>(MongoQueryable.Where <T>(IMongoCollectionExtensions.AsQueryable <T>(this.Collection), where), orderBy).ToList <T>()); }
public IList <T> All <TKey>(int page, int total, Expression <Func <T, TKey> > orderBy, Expression <Func <T, bool> > where) { return(MongoQueryable.Take <T>(MongoQueryable.Skip <T>(MongoQueryable.OrderBy <T, TKey>(MongoQueryable.Where <T>(IMongoCollectionExtensions.AsQueryable <T>(this.Collection), where), orderBy), (page - 1) * total), total).ToList <T>()); }
public async Task <T> FindAsync(Expression <Func <T, bool> > where) { IFindFluent <T, T> findFluent = IMongoCollectionExtensions.Find <T>(this.Collection, where, null); return(await IFindFluentExtensions.FirstOrDefaultAsync <T, T>(findFluent, new CancellationToken())); }
public async Task <T> FindAsync(FilterDefinition <T> query) { IFindFluent <T, T> findFluent = IMongoCollectionExtensions.Find <T>(this.Collection, query, null); return(await IFindFluentExtensions.FirstOrDefaultAsync <T, T>(findFluent, new CancellationToken())); }
public T Find(Expression <Func <T, bool> > where) { return(MongoQueryable.Where <T>(IMongoCollectionExtensions.AsQueryable <T>(this.Collection), where).FirstOrDefault <T>()); }
public async Task <IEnumerable <T> > AllAsync() { IFindFluent <T, T> findFluent = IMongoCollectionExtensions.Find <T>(this.Collection, new BsonDocument(), null); return(await IAsyncCursorSourceExtensions.ToListAsync <T>(findFluent, new CancellationToken())); }
public async Task <IEnumerable <T> > AllAsync <TKey>(int page, int total, Expression <Func <T, bool> > where, Expression <Func <T, TKey> > orderBy) { IOrderedMongoQueryable <T> orderedMongoQueryable = MongoQueryable.OrderBy <T, TKey>(MongoQueryable.Take <T>(MongoQueryable.Skip <T>(MongoQueryable.Where <T>(IMongoCollectionExtensions.AsQueryable <T>(this.Collection), where), (page - 1) * total), total), orderBy); return(await IAsyncCursorSourceExtensions.ToListAsync <T>(orderedMongoQueryable, new CancellationToken())); }
public long Count() { return(IMongoCollectionExtensions.AsQueryable <T>(this.Collection).LongCount <T>()); }
public long Count(Expression <Func <T, bool> > query) { return(IMongoCollectionExtensions.AsQueryable <T>(this.Collection).LongCount <T>(query)); }