/// <summary> /// Appends a match stage to the pipeline. /// </summary> /// <typeparam name="TDocument">The type of the document.</typeparam> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="source">The source.</param> /// <param name="filter">The filter.</param> /// <returns>The fluent aggregate interface.</returns> public static IAggregateFluent <TDocument, TResult> Match <TDocument, TResult>(this IAggregateFluent <TDocument, TResult> source, Expression <Func <TResult, bool> > filter) { Ensure.IsNotNull(source, "source"); Ensure.IsNotNull(filter, "filter"); return(source.Match(filter)); }
/// <summary> /// Appends a match stage to the pipeline. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="aggregate">The aggregate.</param> /// <param name="filter">The filter.</param> /// <returns> /// The fluent aggregate interface. /// </returns> public static IAggregateFluent <TResult> Match <TResult>(this IAggregateFluent <TResult> aggregate, Expression <Func <TResult, bool> > filter) { Ensure.IsNotNull(aggregate, nameof(aggregate)); Ensure.IsNotNull(filter, nameof(filter)); return(aggregate.Match(new ExpressionFilterDefinition <TResult>(filter))); }
private void setupTournamentHands(TreeNode parentNode, PokerFormat format) { DatabaseHandler databaseHandler = DatabaseHandler.getInstance(); IAggregateFluent <TournamentSummary> tournaments = databaseHandler.GetAllTournaments() .Aggregate().Match(Builders <TournamentSummary> .Filter.Where(h => h.SitAndGo == (format == PokerFormat.SitAndGo))); IAggregateFluent <HandHistory> allHands = databaseHandler.GetAllHands().Aggregate() .Match(Builders <HandHistory> .Filter.Where(h => h.GameDescription.PokerFormat == format)); IEnumerable <AggregateResult <Buyin> > allBuyins = tournaments.Group(h => h.Buyin, h => new AggregateResult <Buyin> { result = h.Key }) .Sort(Builders <AggregateResult <Buyin> > .Sort.Ascending(b => b.result)) .ToEnumerable(); decimal lastBuyin = -0.01m; foreach (dynamic buyinObj in allBuyins) { Buyin buyin = buyinObj.result; if (buyin.Total == lastBuyin) { continue; } lastBuyin = buyin.Total; IAggregateFluent <HandHistory> hands = allHands.Match(Builders <HandHistory> .Filter.Where(h => h.GameDescription.TournamentSummary.Buyin.Total == buyin.Total)); GroupHandTreeNode buyinNode = new GroupHandTreeNode(string.Format("{0}{1} {2}", buyin.GetCurrencySymbol(), buyin.Total, HandCount(hands)), hands); dynamic allIds = hands.Group(h => h.GameDescription.TournamentId, h => new { name = h.Key }).ToEnumerable(); foreach (dynamic idObj in allIds) { string id = idObj.name; if (!string.IsNullOrWhiteSpace(id)) { IEnumerable <TournamentSummary> summaries = tournaments.Match(t => t.Id == id).ToEnumerable(); if (summaries.Count() > 0) { TournamentSummary summary = summaries.First(); IAggregateFluent <HandHistory> tournyHands = allHands.Match(Builders <HandHistory> .Filter.Where(h => h.GameDescription.TournamentId == summary.Id)); buyinNode.Nodes.Add(new HandsTreeNode(summary.ToString(), tournyHands)); } } } if (buyinNode.Nodes.Count > 0) { parentNode.Nodes.Add(buyinNode); } } }
protected virtual IAggregateFluent <TEntity> ApplyDataFilters(IAggregateFluent <TEntity> aggregate) { if (typeof(ISoftDelete).IsAssignableFrom(typeof(TEntity))) { aggregate = aggregate.Match(e => ((ISoftDelete)e).IsDeleted == false); } return(aggregate); }
public IAggregateFluent <T> Match <T>(IAggregateFluent <T> source) { var firstVisitor = OrderVisitors[0]; var filter = (firstVisitor is AscendingVisitor) ? Builders <T> .Filter.Lte(firstVisitor.Property, Start) : Builders <T> .Filter.Gte(firstVisitor.Property, Start); return(source.Match(filter)); }
/// <summary> /// /// </summary> /// <param name="filter"></param> /// <param name="sort"></param> /// <param name="readPreference"></param> /// <returns></returns> protected IAggregateFluent <TEntity> CreateAggregate(FilterDefinition <TEntity> filter, SortDefinition <TEntity> sort, ReadPreference readPreference = null) { IAggregateFluent <TEntity> aggregateFluent = this.GetCollection(readPreference).Aggregate(null); aggregateFluent = aggregateFluent.Match(filter); if (sort != null) { aggregateFluent = aggregateFluent.Sort(sort); } return(aggregateFluent); }
private IAggregateFluent <PostCompleteDbModel> ApplyFilter( IAggregateFluent <PostCompleteDbModel> baseQuery, string filter) { if (string.IsNullOrWhiteSpace(filter)) { return(baseQuery); } filter = filter .ToUpperInvariant() .Trim(); return(baseQuery.Match(post => post.Title .ToUpperInvariant() .Contains(filter))); }
public void SetupHandTreeView() { DatabaseHandler databaseHandler = DatabaseHandler.getInstance(); IMongoCollection <HandHistory> allHands = databaseHandler.GetAllHands(); IAggregateFluent <HandHistory> cashHands = allHands.Aggregate().Match(Builders <HandHistory> .Filter.Where(h => h.GameDescription.PokerFormat == PokerFormat.CashGame)); GroupHandTreeNode cashGamesNode = new GroupHandTreeNode("Cash Games", cashHands); IEnumerable <AggregateResult <Limit> > limits = cashHands.Group(h => h.GameDescription.Limit, h => new AggregateResult <Limit> { result = h.Key }) .Sort(Builders <AggregateResult <Limit> > .Sort.Ascending(l => l.result.BigBlind).Ascending(l => l.result.SmallBlind)) .ToEnumerable(); foreach (AggregateResult <Limit> limit in limits) { IAggregateFluent <HandHistory> hands = cashHands.Match(Builders <HandHistory> .Filter.Where(h2 => h2.GameDescription.Limit.Equals(limit.result))); cashGamesNode.Nodes.Add( new HandsTreeNode(string.Format("{0} {1}", limit.result.ToString(), HandCount(hands)), hands)); } HandView.Nodes.Add(cashGamesNode); TreeNode sitAndGoNode = new TreeNode("Sit and Go"); setupTournamentHands(sitAndGoNode, PokerFormat.SitAndGo); HandView.Nodes.Add(sitAndGoNode); TreeNode tournamentNode = new TreeNode("Tournaments"); setupTournamentHands(tournamentNode, PokerFormat.MultiTableTournament); HandView.Nodes.Add(tournamentNode); HandView.BeforeExpand += BeforeExpand; HandView.AfterCollapse += AfterCollapse; HandView.ContextMenuStrip = new ContextMenuStrip(); HandView.ContextMenuStrip.Items.Add(new QuickViewMenuItem(this)); HandView.ContextMenuStrip.Items.Add(new ToolStripMenuItem("&Setup custom view...", null, (s, e) => SetupCustomView())); }
public List <T> GetPagination(FilterDefinition <T> filter, SortDefinition <T> sorter, ProjectionDefinition <T> projection, ref PagerInfo pagerInfo) { IMongoCollection <T> myCollection = GetCollection(); AggregateOptions opts = new AggregateOptions() { AllowDiskUse = true, BatchSize = int.MaxValue, MaxTime = TimeSpan.FromMinutes(10) }; IAggregateFluent <T> aggregate = GetAggregateFluent(opts); if (filter == null) { filter = Builders <T> .Filter.Empty; } aggregate = aggregate.Match(filter); if (sorter != null) { aggregate.Sort(sorter); } if (projection != null) { aggregate = aggregate.Project <T>(projection); } pagerInfo.Total = myCollection.CountAsync(filter).GetAwaiter().GetResult(); //List<T> result = finder // .Skip((pagerInfo.Page) * pagerInfo.PageSize) // .Limit(pagerInfo.PageSize) // .ToListAsync().GetAwaiter().GetResult(); List <T> result = myCollection.Aggregate(opts).Match(filter).Sort(sorter) .Skip((pagerInfo.Page) * pagerInfo.PageSize) .Limit(pagerInfo.PageSize).ToListAsync <T>().GetAwaiter().GetResult(); return(result); }
public void ShouldFetchCandidateListWhenSectorWiseSearch() { IMongoDatabase database = GetMongoDatabase(); IMongoCollection <BsonDocument> candidateCollection = database.GetCollection <BsonDocument>("Candidates"); IMongoCollection <BsonDocument> companyCollection = database.GetCollection <BsonDocument>("Companies"); var sectors = new[] { "java" }; IAggregateFluent <BsonDocument> candidateAgg = candidateCollection.Aggregate(); var let = new BsonDocument("compId", "$PreferredCompanies"); var operands = new BsonArray(); operands.Add("$$compId").Add("$_id"); var expression = new BsonDocument("$expr", new BsonDocument("$eq", operands)); PipelineDefinition <BsonDocument, BsonDocument> pipeline = PipelineDefinition <BsonDocument, BsonDocument> .Create(new BsonDocument("$match", expression)); candidateAgg = candidateAgg.Lookup(companyCollection, let, pipeline, "Array"); candidateAgg = candidateAgg.Unwind("Array"); FilterDefinition <BsonDocument> sectorFilters = Builders <BsonDocument> .Filter.In("Array.sectors", sectors); candidateAgg = candidateAgg.Match(sectorFilters); var fields = new BsonDocument { { "_id", "$_id" }, { "CompanyId", new BsonDocument { { "$first", "$CompanyId" } } } }; candidateAgg = candidateAgg.Group(fields); IEnumerable <BsonDocument> resultList = candidateAgg.ToList(); Assert.NotNull(resultList); }
/// <summary> /// Applies filtering sorting and projections on the <see cref="IExecutable{T}.Source"/> /// </summary> /// <returns>A aggregate fluent including the configuration of this executable</returns> public IAggregateFluent <T> BuildPipeline() { IAggregateFluent <T> pipeline = _aggregate; if (Sorting is not null) { pipeline = pipeline.Sort(Sorting.ToSortDefinition <T>()); } if (Filters is not null) { pipeline = pipeline.Match(Filters.ToFilterDefinition <T>()); } if (Projection is not null) { pipeline = pipeline.Project <T>(Projection.ToProjectionDefinition <T>()); } return(pipeline); }
/// <summary> /// Restituisce la posizione dei mezzi per i quali non c'è un messaggio sufficientemente recente /// </summary> /// <param name="daSecondi">Numero di secondi entro i quali non è presente un messaggio</param> /// <param name="classiMezzo">Le classi mezzo da filtrare</param> /// <returns>Messaggi posizione meno recenti</returns> public IEnumerable <MessaggioPosizione> Get(int daSecondi, string[] classiMezzo) { IAggregateFluent <MessaggioPosizione_DTO> query = this.messaggiPosizione.Aggregate <MessaggioPosizione_DTO>() .SortBy(m => m.CodiceMezzo) .ThenByDescending(m => m.IstanteAcquisizione); if (classiMezzo != null && classiMezzo.Length > 0) { var filter = Builders <MessaggioPosizione_DTO> .Filter .AnyIn(m => m.ClassiMezzo, classiMezzo); query = query .Match(filter); } var query2 = query .Group(BsonDocument.Parse(@"{ _id: '$codiceMezzo', messaggio: { $first: '$$ROOT' } }")) .Match(new BsonDocument { { "messaggio.istanteAcquisizione", new BsonDocument { { "$lt", DateTime.Now.AddSeconds(-daSecondi) } } } }) .Project(BsonDocument.Parse(@"{ _id: 0, messaggio: 1 }")); var resultSet = query2 .ReplaceRoot <MessaggioPosizione_DTO>("$messaggio") .ToEnumerable() .Select(dto => dto.ConvertToDomain()); return(resultSet); }
/// <summary> /// Appends a match stage to the pipeline with a filter expression /// </summary> /// <typeparam name="T">Any class that implements IEntity</typeparam> /// <param name="aggregate"></param> /// <param name="filter">f => f.Eq(x => x.Prop, Value) & f.Gt(x => x.Prop, Value)</param> public static IAggregateFluent <T> Match <T>(this IAggregateFluent <T> aggregate, Func <FilterDefinitionBuilder <T>, FilterDefinition <T> > filter) where T : IEntity { return(aggregate.Match(filter(Builders <T> .Filter))); }
/// <summary> /// Return establishment list. /// </summary> /// <param name="filter"></param> /// <returns></returns> public ListResult <EstablishmentListDTO> List(EstablishmentFilter filter) { IAggregateFluent <Establishment> establishmentAggregateFluent = this.MongoRepository .GetCollection <Establishment>().Aggregate(); if (filter.GeospatialQuery) { if (!filter.Meters.HasValue) { filter.Meters = 10000; } BsonDocument geoNearOptions = new BsonDocument { { "near", new BsonDocument { { "type", "Point" }, { "coordinates", new BsonArray { filter.Longitude.Value, filter.Latitude.Value } }, } }, { "maxDistance", filter.Meters }, { "includeLocs", "Location.Coordinates" }, { "distanceField", "Location.Distance" }, { "spherical", true } }; establishmentAggregateFluent = establishmentAggregateFluent.AppendStage( (PipelineStageDefinition <Establishment, Establishment>) new BsonDocument { { "$geoNear", geoNearOptions } } ); this.TelemetryClient.TrackEvent( EventNames.EstablishmentListLocation, new { filter.Latitude, filter.Longitude } ); } if (filter.EstablishmentType.HasValue) { establishmentAggregateFluent = establishmentAggregateFluent .Match(document => document.EstablishmentTypes.Contains(filter.EstablishmentType.Value)); this.TelemetryClient.TrackEvent( EventNames.EstablishmentListType, new { filter.EstablishmentType } ); } if (!string.IsNullOrEmpty(filter.Query)) { establishmentAggregateFluent = establishmentAggregateFluent.Match( document => document.Name.Contains(filter.Query) || document.Description.Contains(filter.Query) ); this.TelemetryClient.TrackEvent( EventNames.EstablishmentListQuery, new { filter.Query } ); } if (filter.DaysOfWeekEnum != null) { Expression <Func <Establishment, bool> > availabilityExpression = document => false; foreach (DayOfWeekEnum dayOfWeek in filter.DaysOfWeekEnum) { availabilityExpression = availabilityExpression.Or( document => document.Availabilities.Any( availability => availability.DayOfWeek == dayOfWeek || availability.CloseDayOfWeek == dayOfWeek ) ); } establishmentAggregateFluent = establishmentAggregateFluent.Match(availabilityExpression); this.TelemetryClient.TrackEvent( EventNames.EstablishmentListDaysOfWeek, new { filter.DaysOfWeek } ); } IAggregateFluent <BsonDocument> aggregateFluent = establishmentAggregateFluent.As <BsonDocument>(); aggregateFluent = filter.OrderType == OrderTypeEnum.Distance ? aggregateFluent.SortBy(document => document["Location"]["Distance"]) : aggregateFluent.SortByDescending(document => document["Relevance"]); if (!this.UserContext.EstablishmentId.HasValue) { this.RelevanceService.Register <Establishment, EstablishmentFilter>(filter); } IEnumerable <BsonDocument> documents = aggregateFluent .Skip((filter.Page - 1) * filter.PageSize) .Limit(filter.PageSize) .ToList(); IEnumerable <EstablishmentListDTO> establishments = documents.Select(document => new EstablishmentListDTO { Id = document["_id"].AsObjectId, EstablishmentTypes = document["EstablishmentTypes"].AsBsonArray.Select(x => (EstablishmentTypeEnum)x.AsInt32), ImageThumbnail = document["ImageThumbnail"]["Uri"].AsString, Name = document["Name"].AsString, Distance = document["Location"].AsBsonDocument.Contains("Distance") ? document["Location"]["Distance"].AsDouble : (double?)null } ).ToList(); return(new ListResult <EstablishmentListDTO>( establishments, aggregateFluent.Count().FirstOrDefault()?.Count ?? 0, filter )); }
/// <summary> /// Return event list. /// </summary> /// <returns></returns> public ListResult <EventListDTO> List(EventFilter filter) { IAggregateFluent <Event> eventAggregateFluent = this.MongoRepository.GetCollection <Event>().Aggregate(); if (filter.GeospatialQuery) { if (!filter.Meters.HasValue) { filter.Meters = 10000; } BsonDocument geoNearOptions = new BsonDocument { { "near", new BsonDocument { { "type", "Point" }, { "coordinates", new BsonArray { filter.Longitude.Value, filter.Latitude.Value } }, } }, { "maxDistance", filter.Meters }, { "includeLocs", "Location.Coordinates" }, { "distanceField", "Location.Distance" }, { "spherical", true } }; eventAggregateFluent = eventAggregateFluent.AppendStage( (PipelineStageDefinition <Event, Event>) new BsonDocument { { "$geoNear", geoNearOptions } } ); this.TelemetryClient.TrackEvent( EventNames.EventListLocation, new { filter.Latitude, filter.Longitude } ); } if (!string.IsNullOrEmpty(filter.EstablishmentId)) { eventAggregateFluent = eventAggregateFluent.Match( document => document.EstablishmentId == new ObjectId(filter.EstablishmentId)); this.TelemetryClient.TrackEvent( EventNames.EventListEstablishment, new { filter.EstablishmentId } ); } if (filter.Genre.HasValue) { eventAggregateFluent = eventAggregateFluent.Match( document => document.Genres.Contains(filter.Genre.Value)); this.TelemetryClient.TrackEvent( EventNames.EventListGenre, new { filter.Genre } ); } if (!string.IsNullOrEmpty(filter.Query)) { eventAggregateFluent = eventAggregateFluent.Match( document => document.Name.Contains(filter.Query) || document.Description.Contains(filter.Query) ); this.TelemetryClient.TrackEvent( EventNames.EventListQuery, new { filter.Query } ); } if (filter.DateFilter) { eventAggregateFluent = eventAggregateFluent.Match(document => ( (document.EndDate >= filter.StartDate && document.StartDate <= filter.StartDate) || (document.StartDate <= filter.EndDate && document.EndDate >= filter.EndDate) || (document.StartDate >= filter.StartDate && document.EndDate <= filter.EndDate) )); this.TelemetryClient.TrackEvent( EventNames.EventListDate, new { filter.StartDate, filter.EndDate } ); } if (!this.UserContext.EstablishmentId.HasValue) { this.RelevanceService.Register <Event, EventFilter>(filter); } IAggregateFluent <BsonDocument> aggregateFluent = eventAggregateFluent.Lookup( nameof(Establishment), "EstablishmentId", "_id", "Establishment" ).Unwind("Establishment"); aggregateFluent = filter.OrderType == OrderTypeEnum.Distance ? aggregateFluent.SortBy(document => document["Location"]["Distance"]) : aggregateFluent.SortByDescending(document => document["Relevance"]); IEnumerable <BsonDocument> documents = aggregateFluent .Skip((filter.Page - 1) * filter.PageSize) .Limit(filter.PageSize) .ToList(); IEnumerable <EventListDTO> events = documents.Select(document => new EventListDTO { Id = document["_id"].AsObjectId, Name = document["Name"].AsString, StartDate = document["StartDate"].ToUniversalTime(), EndDate = document["EndDate"].ToUniversalTime(), Genres = document["Genres"].AsBsonArray.Select(x => (GenreEnum)x.AsInt32), ImageThumbnail = document["ImageThumbnail"]["Uri"].AsString, Distance = document["Location"].AsBsonDocument.Contains("Distance") ? document["Location"]["Distance"].AsDouble : (double?)null, Establishment = new EventListEstablishmentDTO { Id = document["EstablishmentId"].AsObjectId, Name = document["Establishment"]["Name"].AsString, ImageThumbnail = document["Establishment"]["ImageThumbnail"]["Uri"].AsString, } } ).ToList(); return(new ListResult <EventListDTO>( events, aggregateFluent.Count().FirstOrDefault()?.Count ?? 0, filter )); }