/// <summary> /// 构造排序 /// </summary> /// <param name="interfaceSortId"></param> /// <returns></returns> private SortDefinition <BsonDocument> StructureSortDefinition(Guid interfaceSortId) { var builder = new SortDefinitionBuilder <BsonDocument>(); SortDefinition <BsonDocument> sort = null; if (interfaceSortId == Guid.Empty) { return(builder.Ascending("_id")); } var sorts = _interfaceSortRepository.GetInterfaceSortByParentId(interfaceSortId) ?? new List <InterfaceSort>(0); foreach (var item in sorts) { switch (item.GetSortType()) { case SortTypeEnum.DESC: sort = sort?.Descending(item.MetaFieldShortCode) ?? builder.Descending(item.MetaFieldShortCode); break; case SortTypeEnum.ASC: sort = sort?.Ascending(item.MetaFieldShortCode) ?? builder.Ascending(item.MetaFieldShortCode); break; default: break; } } return(sort); }
public List <BsonDocument> GetList(int tenantId, MetaObject metaObject, FilterDefinition <BsonDocument> condition, int pageIndex, int pageSize, SortDefinition <BsonDocument> sort, string[] columns = null) { List <BsonDocument> bson = new List <BsonDocument>(); if (pageSize == 0) { //无条件默认取10000条 pageSize = 1000; } var projection = Builders <BsonDocument> .Projection.Include("_id"); //include fields if (columns != null && columns.Any()) { foreach (var item in columns) { projection = projection.Include(item); } } int skipSize = (pageIndex - 1) > 0 ? ((pageIndex - 1) * pageSize) : 0; if (sort == null) { sort = new SortDefinitionBuilder <BsonDocument>().Ascending("_id"); } bson = db.GetCollectionBson(metaObject.Code).Find(CombineTenantId(tenantId, condition)).Skip(skipSize).Limit(pageSize).Sort(sort).Project(projection).ToList(); return(bson); }
private int getHighestID() { int rval = 0; rotateCollection(); BsonDocument query = new BsonDocument(); //TODO Refactor the query for 3.0 driver BsonDocument limits = new BsonDocument("$gt", new BsonDocument("w", workerID)); limits.Add("$lt", new BsonDocument("w", workerID + 1)); query.Add("_id", limits); var projection = new ProjectionDefinitionBuilder <BsonDocument>() .Include("_id"); var sort = new SortDefinitionBuilder <BsonDocument>() .Descending("_id"); BsonDocument myDoc = coll.Find(query) .Project(projection) .Sort(sort) .FirstOrDefault(); if (myDoc != null) { BsonDocument id = (BsonDocument)myDoc.GetValue("_id"); rval = id.GetValue("i").AsInt32 + 1; } return(rval); }
SortDefinition <TEntity> BuildSortDefinitionFromFilterOptions(FilterOptions <TEntity> filterOptions) { if (filterOptions?.SortFields == null) { return(null); } var builder = new SortDefinitionBuilder <TEntity>(); SortDefinition <TEntity> sortDefinition = null; foreach (var sortField in filterOptions.SortFields) { switch (sortField.Order) { case FilterOptions <TEntity> .SortOrderEnum.Ascending: sortDefinition = sortDefinition?.Ascending(sortField.Field) ?? builder.Ascending(sortField.Field); break; case FilterOptions <TEntity> .SortOrderEnum.Descending: sortDefinition = sortDefinition?.Descending(sortField.Field) ?? builder.Descending(sortField.Field); break; } } return(sortDefinition); }
private static PipelineDefinition <BsonDocument, BsonDocument> GetLookupPipeline() { var sortBuilder = new SortDefinitionBuilder <BsonDocument>(); var relationSortDefinition = sortBuilder.Ascending("_id"); var lookupPipeline = new EmptyPipelineDefinition <BsonDocument>() .Match(new BsonDocument("$expr", new BsonDocument("$and", new BsonArray { new BsonDocument("$eq", new BsonArray { "Customer_id", "$$parentId" }), new BsonDocument("$not", new BsonArray { new BsonDocument("$in", new BsonArray { "Status", new BsonArray("Cancelled,OnHold") }) }) }))) .Sort(relationSortDefinition) .Project("{_id: 1, Status:1}"); return(lookupPipeline); }
public SortDefinition <T> FilterConditionToSort <T>(List <FilterCondition> filter) { SortDefinitionBuilder <T> sort = Builders <T> .Sort; SortDefinition <T> sd = null; if (filter == null) { return(sd); } foreach (FilterCondition s in filter) { if (!s.OrderType.HasValue) { continue; } if (s.OrderType == TableOrderType.DESCENDING) { sd = sort.Combine(sort.Descending(s.Key)); } else { sd = sort.Combine(sort.Ascending(s.Key)); } } return(sd); }
private DataTable ViewData_() { IMongoCollection <BsonDocument> coll = db.GetCollection <BsonDocument>(wordName); //创建生成器 FilterDefinitionBuilder <BsonDocument> builderFilter = Builders <BsonDocument> .Filter; //排序生成器 SortDefinitionBuilder <BsonDocument> builderSort = Builders <BsonDocument> .Sort; //排序约束 Ascending 正序 Descending 倒序 SortDefinition <BsonDocument> sort = builderSort.Ascending("English"); var result = coll.Find <BsonDocument>(builderFilter.Empty).Sort(sort).ToList(); //创建一个空表 DataTable dt = new DataTable(); dt.Columns.Add("Id", typeof(String)); dt.Columns.Add("Chinese", typeof(String)); dt.Columns.Add("English", typeof(String)); dt.Columns.Add("paraphraseC", typeof(String)); dt.Columns.Add("paraphraseE", typeof(String)); foreach (var item in result) { var id = item["_id"].ToString(); dt.Rows.Add(id, item["Chinese"].AsString, item["English"].AsString, item["paraphraseC"].AsString, item["paraphraseE"].AsString); } return(dt); }
private static SortDefinition <BsonDocument> GetSortDefinition() { var sortBuilder = new SortDefinitionBuilder <BsonDocument>(); var sortDefinition = sortBuilder.Ascending("_id"); return(sortDefinition); }
public SortDefinition <TSort> GetSortDefinition <TSort>(Expression <Func <IEnumerable <TSort>, dynamic> > orderBy) { var stackMember = new Stack <string>(); var stackSortMethod = new Stack <int>(); new SortExpressionParser().Parsing <TSort>(orderBy, stackMember, stackSortMethod); if (stackMember.Any() && stackSortMethod.Any() && stackMember.Count == stackSortMethod.Count) { var length = stackMember.Count; SortDefinitionBuilder <TSort> builder = new SortDefinitionBuilder <TSort>(); List <SortDefinition <TSort> > list = new List <SortDefinition <TSort> >(); for (var i = 0; i < length; i++) { var name = stackMember.Pop(); var way = stackSortMethod.Pop(); if (way == 1) { list.Add(builder.Ascending(name)); } else { list.Add(builder.Descending(name)); } } var definition = builder.Combine(list); return(definition); } return(null); }
public static SortDefinition <T> Sort__ <T, SortType>(this SortDefinitionBuilder <T> builder, Expression <Func <T, SortType> > field, bool desc) { if (field.Body is MemberExpression exp) { var parameter_type = field.Parameters.FirstOrDefault()?.Type; parameter_type.Should().NotBeNull(); var parameter = Expression.Parameter(parameter_type, "x"); var member = Expression.Property(parameter, propertyName: exp.Member.Name); Expression body = member; var sort_field = Expression.Lambda <Func <T, object> >(body: body, parameters: new[] { parameter }); if (desc) { return(builder.Descending(sort_field)); } else { return(builder.Ascending(sort_field)); } } else { throw new NotSupportedException("不支持的排序lambda表达式"); } }
public Task <List <TDocument> > GetAsync(int page, Expression <Func <TDocument, bool> > expression, Tuple <Expression <Func <TDocument, object> >, SortingType> sort = null, CancellationToken cancellationToken = default(CancellationToken)) { var currentPage = page < 0 ? 0 : page - 1; IFindFluent <TDocument, TDocument> findFluent; if (IsInTransaction()) { findFluent = Collection.Find(this.clientSessionHandle, expression); } else { findFluent = Collection.Find(expression); } var find = findFluent .Skip(currentPage * 1000) .Limit(1000); if (sort != default(Tuple <Expression <Func <TDocument, object> >, SortingType>)) { var builder = new SortDefinitionBuilder <TDocument>(); var sortByDefinition = sort.Item2 == SortingType.Ascending ? builder.Ascending(sort.Item1) : builder.Descending(sort.Item1); find = find.Sort(sortByDefinition); } return(find.ToListAsync(cancellationToken)); }
public PagedResponse <Archivo> BusquedaPaginada(ArchivoFiltro filtro) { var pr = new PagedResponse <Archivo> { Data = new List <Archivo>() }; //Filter string id = filtro.id ?? ""; var sort = new SortDefinitionBuilder <Datos.NoSQL.Modelo.Archivo>().Descending(x => x.fechaCreacion); var r = _archivoRepositorio.FindPaged(filtro, //x => (x.esBorrado == false && (x.id == (id.Length == 0 ? x.id : ObjectId.Parse(id)))), x => (x.esBorrado == false), sort); //To foreach (var item in r.Data) { pr.Data.Add(new Archivo { nombre = item.nombre, fechaCreacion = item.fechaCreacion, id = item.id.ToString(), versiones = GetVersiones(item.id.ToString()) }); } pr.TotalPages = r.TotalPages; pr.TotalRows = r.TotalRows; return(pr); }
public void Import(IEnumerable <Employee> employees) { var positions = _db.GetCollection <Speciality>("Positions").Find(x => true).ToList(); var specialities = _db.GetCollection <Speciality>("Specialities").Find(x => true).ToList(); var duties = _db.GetCollection <Speciality>("Duties").Find(x => true).ToList(); var siteId = Properties.Settings.Default.siteId; SortDefinition <Employee> empMaxIdDef = new SortDefinitionBuilder <Employee>().Descending("EmployeeId"); var maxEmpId = _db.GetCollection <Employee>("Employees").Find(x => true).Sort(empMaxIdDef).Limit(1).Single(); var nextEmpId = maxEmpId.EmployeeId; var emps = new List <Employee>(); var pwds = new Dictionary <int, string>(); try { foreach (var emp in employees) { emp.SiteId = siteId; emp.EmployeeId = ++nextEmpId; if (emps.Any(x => x.ContactInfo.EMail == emp.ContactInfo.EMail)) //add extra duty to existing employee { var existing = emps.First(x => x.ContactInfo.EMail == emp.ContactInfo.EMail); var dList = existing.Duties.ToList(); dList.AddRange(emp.Duties); existing.Duties = dList; nextEmpId = emp.EmployeeId; } else { pwds.Add(emp.EmployeeId, emp.Tag.ToString()); emp.Tag = null; emps.Add(emp); } } _db.GetCollection <Employee>("Employees").InsertMany(emps); //duplicate email //var q1 = emps.GroupBy(g=>g.ContactInfo.EMail) // .Where(g => g.Count() > 1) //.Select(y => y.Key) //.ToList(); //non valid email //checkEmail(emps.Select(x => x.ContactInfo.EMail)); foreach (var emp in emps) { emp.Tag = pwds[emp.EmployeeId]; //await DDR.API.Proxies.Auth.CreateUser(emp); } Console.WriteLine(string.Format("Imported {0} users", emps.Count)); } catch (Exception exc) { var q = exc; } }
public async Task <IEnumerable <Branch> > Run(string[] selectedCategories = null, string partnerName = null) { var filter = new FilterDefinitionBuilder <Branch>().Where(x => !x.IsDeleted); if (selectedCategories != null) { var byCategoriesFilter = new FilterDefinitionBuilder <Branch>().Where(x => x.CategoryIds == null || !x.CategoryIds.Any() || x.CategoryIds.Any(i => selectedCategories.Contains(i))); filter = new FilterDefinitionBuilder <Branch>().And(filter, byCategoriesFilter); } if (!string.IsNullOrEmpty(partnerName)) { partnerName = partnerName.ToLower().Trim(); var byPartnerNameFilter = new FilterDefinitionBuilder <Branch>().Where(x => x.Name.Any(y => y.LocText.ToLower().Trim().Contains(partnerName)) || x.Description.Any(y => y.LocText.ToLower().Trim().Contains(partnerName))); filter = new FilterDefinitionBuilder <Branch>().And(filter, byPartnerNameFilter); } // TODO starting with mongoDb server 3.6+ versions we should use expr operator to get data in a one requst instead of two as below // var exprFilter = new BsonDocument("$expr", new BsonDocument("$eq", new BsonArray(new[] { "$_id", "$PartnerId" }))); var partnerIds = await Collection. Aggregate(). Match(filter). Group(x => x.PartnerId, g => new { g.Key }).ToListAsync(); var ids = partnerIds.Select(p => p.Key).ToList(); var filterByIds = new FilterDefinitionBuilder <Branch>().In(x => x.Id, ids); var filterSorting = new SortDefinitionBuilder <Branch>().Descending(b => b.Modified); var result = await Collection. Aggregate(). Match(filterByIds). Sort(filterSorting). Project(p => new Branch { PartnerId = p.PartnerId, Name = p.Name, Description = p.Description, Address = p.Address, Location = p.Location, Phones = p.Phones, Timetable = p.Timetable, CategoryIds = p.CategoryIds, Url = p.Url, Discounts = p.Discounts, Modified = p.Modified, IsDeleted = p.IsDeleted }).ToListAsync(); result.ForEach(e => e.Id = e.PartnerId); return(result); }
public ItemList Query(string collection, DataQuery query) { FilterDefinition <BsonDocument> filter = FilterDefinition <BsonDocument> .Empty; var dataContext = new Dictionary <string, object>(); dataContext["expando"] = query.Expando; if (query.RawQuery != null) { filter = new JsonFilterDefinition <BsonDocument>(query.RawQuery); } InvokeAlterQuery(collection, filter); IFindFluent <BsonDocument, BsonDocument> results = _mongoService .GetCollection <BsonDocument>(collection).Find <BsonDocument>(filter) .Skip((query.PageNumber - 1) * query.PageSize) .Limit(query.PageSize); if (query.Sort != null) { var sort = new SortDefinitionBuilder <BsonDocument>(); SortDefinition <BsonDocument> sortDef = null; foreach (var sortable in query.Sort) { FieldDefinition <BsonDocument> field = sortable.Field; if (sortable.Ascending) { sortDef = (sortDef == null) ? sort.Ascending(field) : sortDef.Ascending(field); } else { sortDef = (sortDef == null) ? sort.Descending(field) : sortDef.Descending(field); } } results = results.Sort(sortDef); } long count = Count(collection, filter); List <BsonDocument> list = results.ToList(); //sanitize id format foreach (BsonDocument item in list) { item["_id"] = item["_id"].ToString(); } string json = list.ToJson(js); var result = JArray.Parse(json); for (int i = 0; i < result.Count; i++) { var node = (JObject)result[i]; InvokeProcess(collection, ref node, PipelineStage.PostOperation, DataOperation.Read, dataContext); } return(new ItemList(result, (int)count, query.PageNumber, query.PageSize)); }
public void PipelineDefinitionCanBeBuild() { var orderByArguments = "index ASC, timestamp DESC"; JsonPipelineStageDefinition <BsonDocument, BsonDocument> stage = null; Assert.That(() => stage = SortDefinitionBuilder.Build <BsonDocument>(orderByArguments), Throws.Nothing); Assert.That(stage, Is.Not.Null); }
public int SearchBiggestVersionNo() { SortDefinitionBuilder <ShotNoVersionNo> builderSort = Builders <ShotNoVersionNo> .Sort; SortDefinition <ShotNoVersionNo> sort = builderSort.Descending("VersionNo"); var result = MyCollection.Find <ShotNoVersionNo>(Builders <ShotNoVersionNo> .Filter.Empty).Sort(sort).ToList(); return(result[0].VersionNo); }
/// <summary> /// 文档排序 /// </summary> public void Sort() { SortDefinitionBuilder <Model2> sortBuilder = Builders <Model2> .Sort; ////按字段Field2A降序排列 SortDefinition <Model2> sort = sortBuilder.Descending(m => m.Field2A); List <Model2> info = mongoDBService.FindAllList(collectionName, sort); }
public List <T> GetPageAsc(Expression <Func <T, bool> > criteria, Expression <Func <T, object> > ascSort, QueryParams pParams) { var sort = new SortDefinitionBuilder <T>(); var result = _collection.Find(criteria).Sort(sort.Ascending(ascSort)).Skip((pParams.Index - 1) * pParams.Size).Limit( pParams.Size).ToList(); return(result); }
/// <summary> /// Get test results by descending of execution datetime /// </summary> /// <returns></returns> public IEnumerable <object> GetTestResults() { FilterDefinition <TestResultModel> filterBuilder = new FilterDefinitionBuilder <TestResultModel>().Empty; FieldDefinition <TestResultModel> fieldDefinition = "ExecutedDTM"; var sortBuilder = new SortDefinitionBuilder <TestResultModel>().Descending(fieldDefinition); return(db.Find(filterBuilder).Sort(sortBuilder).ToList()); }
/// <summary> /// Get test results by testcase id /// </summary> /// <param name="testCaseId"></param> /// <returns></returns> public IEnumerable <TestResultModel> GetTestResultsByTestCaseId(ObjectId testCaseId) { FilterDefinition <TestResultModel> filterBuilder = new FilterDefinitionBuilder <TestResultModel>() .Eq(filter => filter.TestCase_Id, testCaseId); FieldDefinition <TestResultModel> fieldDefinition = "ExecutedDTM"; var sortBuilder = new SortDefinitionBuilder <TestResultModel>().Descending(fieldDefinition); return(db.Find(filterBuilder).Sort(sortBuilder).ToList()); }
private IEnumerable <TModel> FindAll(FilterDefinition <TModel> filter, QueryOptions <TModel> options) { ProjectionDefinition <TModel> projection = null; foreach (var field in options.Fields) { if (projection == null) { projection = new ProjectionDefinitionBuilder <TModel>().Include(field); } else { projection = projection.Include(field); } } SortDefinition <TModel> sortDefinition = null; var builder = new SortDefinitionBuilder <TModel>(); if (options.SortAscending != null) { sortDefinition = builder.Ascending(options.SortAscending); } if (options.SortDescending != null) { sortDefinition = builder.Descending(options.SortDescending); } IFindFluent <TModel, TModel> result = null; if (projection == null) { result = Collection.Find(filter); } else { result = Collection.Find(filter).Project <TModel>(projection); } if (options.Skip.HasValue) { result.Skip(options.Skip.Value); } if (options.Take.HasValue) { result.Limit(options.Take); } if (sortDefinition != null) { result.Sort(sortDefinition); } return(result.ToEnumerable()); }
public static SortDefinition <BsonDocument> GetCustomerSortDefinition() { var sortBuilder = new SortDefinitionBuilder <BsonDocument>(); var daySortDefinition = sortBuilder.Ascending("Day"); var monthSortDefinition = sortBuilder.Ascending("Month"); var netWorthSortDefinition = sortBuilder.Descending("NetWorth"); var yearSortDefinition = sortBuilder.Ascending("Year"); var sortDefinition = sortBuilder.Combine(daySortDefinition, monthSortDefinition, netWorthSortDefinition, yearSortDefinition); return(sortDefinition); }
/// <summary> /// return a dataset from database /// </summary> /// <param name="DatabaseName"></param> /// <param name="TableName"></param> /// <param name="filterDefinition"></param> /// <param name="SortName"></param> /// <param name="sortMode"></param> /// <returns></returns> public List <Hashtable> GetDataSet(String DatabaseName, String TableName, FilterDefinition <BsonDocument> filterDefinition, String SortName = "", SortMode sortMode = SortMode.Ascending) { if (conn == null) { throw new Exception("Connection has not initialize."); } if (DatabaseName.Length == 0) { throw new Exception("Database Name is not exist."); } IMongoDatabase database = conn.GetDatabase(DatabaseName); if (database.ListCollectionNames().ToList().Contains(TableName) == false) { throw new Exception("Collection Name is not exist in MongoDB Database."); } IMongoCollection <BsonDocument> collection = database.GetCollection <BsonDocument>(TableName); var filter = filterDefinition; List <Hashtable> hr = new List <Hashtable>(); IAsyncCursor <BsonDocument> cursor; if (SortName == "") { cursor = collection.Find(filter).ToCursor(); } else { SortDefinitionBuilder <BsonDocument> builderSort = Builders <BsonDocument> .Sort; SortDefinition <BsonDocument> sort = sortMode == SortMode.Ascending ? builderSort.Ascending(SortName) : builderSort.Descending(SortName); cursor = collection.Find(filter).Sort(sort).ToCursor(); } foreach (var document in cursor.ToEnumerable()) { Hashtable ht = Json2Hashtable(document.ToJson()); hr.Add(ht); } //DataTable dt = HashTableToDataTable(hr); //DataSet ds = new DataSet(); //ds.Tables.Add(dt); return(hr); }
public override async Task <IEnumerable <Article> > GetAll() { SortDefinitionBuilder <Article> builderSort = Builders <Article> .Sort; var sort = builderSort.Descending("_id"); var options = new FindOptions <Article, Article>() { Sort = sort, }; var cursor = await this._collection.FindAsync(new BsonDocument(), options); return(await cursor.ToListAsync()); }
public BaseRepository() { string connectionString = ConfigurationManager.AppSettings["mongodb"]; var client = new MongoClient(connectionString); var database = client.GetDatabase(DbName); Collection = database.GetCollection <T>(typeof(T).Name); Filter = new FilterDefinitionBuilder <T>(); Update = new UpdateDefinitionBuilder <T>(); Sort = new SortDefinitionBuilder <T>(); Projection = new ProjectionDefinitionBuilder <T>(); }
public static Log ReadLatest(MongoConnection connection) { IMongoCollection <Log> logs = connection.Database.GetCollection <Log>(typeof(Log).Name); SortDefinitionBuilder <Log> sortBuilder = new SortDefinitionBuilder <Log>(); SortDefinition <Log> sortDefinition = sortBuilder.Descending(log => log.CreatedTime); IFindFluent <Log, Log> logFind = logs.Find(log => true).Sort(sortDefinition); Task <Log> logTask = logFind.FirstAsync(); return(logTask.Result); }
private static SortDefinition <T> GetSort(IFilter filter) { if (string.IsNullOrEmpty(filter?.SortColumn)) { return(default(SortDefinition <T>)); } var sortDefinition = new SortDefinitionBuilder <T>(); return(filter.isDescending ? sortDefinition.Descending(filter.SortColumn) : sortDefinition.Ascending(filter.SortColumn)); }
public async Task <List <Article> > GetHotArticles() { SortDefinitionBuilder <Article> builderSort = Builders <Article> .Sort; var sort = builderSort.Descending("Meta.Views"); var options = new FindOptions <Article, Article>() { Sort = sort, Limit = 10 }; var cursor = await this._collection.FindAsync(new BsonDocument(), options); return(await cursor.ToListAsync()); }
/// <summary> /// 按照页面查询 /// </summary> public void SelectPageDB(int pageSize, int pageNum) { var persons = from person in collection.AsQueryable() where person.Name == "zq" orderby person.Name ascending select new { Name = person.Name }; SortDefinitionBuilder <BsonDocument> sorDefBui = Builders <BsonDocument> .Sort; SortDefinition <BsonDocument> sorDef = sorDefBui.Ascending("Name"); FilterDefinitionBuilder <BsonDocument> filDefBui = Builders <BsonDocument> .Filter; collectionBD.Find(filDefBui.Empty).Sort(sorDef).SortBy(t => t["Name"]); }
public ListResponse<EventCategory> ListEventCategories() { var response = new ListResponse<EventCategory>(); try { var clnEventCategories = this.StatWinnerDatabase.GetCollection<EventCategoryDBEntity>("EventCategories"); var sortDefinition = new SortDefinitionBuilder<EventCategoryDBEntity>(); var lst = clnEventCategories.Find(_ => true) .Sort(sortDefinition.Ascending(s => s.Name)) .ToListAsync() .Result.Select(EventManagementFactory.ConvertToEventCategory) .ToList(); response.Result = lst; } catch (Exception ex) { response.SetError(ex); } return response; }
public ListResponse<Country> LoadAllCountries() { var response = new ListResponse<Country>(); try { var mongoCollection = this.StatWinnerDatabase.GetCollection<CountryEntity>("Countries"); var sortDefinition = new SortDefinitionBuilder<CountryEntity>(); var lst = mongoCollection.Find(_ => true) .Sort(sortDefinition.Ascending("name")) .ToListAsync() .Result.Select(UserAccountManagementFactory.convertToCountry) .ToList(); response.Result = lst; } catch (Exception ex) { response.SetError(ex); } return response; }
/// <summary> /// Loads the list of notification events /// </summary> /// <returns></returns> public ListResponse<EventEntity> LoadNotificationEvents() { var response = new ListResponse<EventEntity>(); try { var clnEvents = this.StatWinnerDatabase.GetCollection<EventDbEntity>("NotificationEvents"); var sortDefinition = new SortDefinitionBuilder<EventDbEntity>(); var events = clnEvents.Find(_ => true).Sort(sortDefinition.Ascending(r => r.EventKey)).ToListAsync().Result.Select(EventManagementFactory.ConvertToEvent).ToList(); //Set Event Categories var clnEventCategories = this.StatWinnerDatabase.GetCollection<EventCategoryDBEntity>("EventCategories"); var evenTcategoriIds = events.Where(e => !e.EventCategoryId.IsNullOrEmpty()).Select(e => ObjectId.Parse(e.EventCategoryId)).ToList(); var eventCategoriesFilter = Builders<EventCategoryDBEntity>.Filter.In("_id", evenTcategoriIds); var eventCategories = clnEventCategories.Find(eventCategoriesFilter).ToListAsync().Result.ToList(); events.ForEach(ev => ev.EventCategoryName = (eventCategories.Single(ec => ec.Id.ToString() == ev.EventCategoryId).Name)); response.Result = events; } catch (Exception ex) { response.SetError(ex); } return response; }