コード例 #1
0
        public static IAggregateFluent <T> QuerySkip <T>(this IAggregateFluent <T> cursor, ClrQuery query)
        {
            if (query.Skip > 0)
            {
                cursor = cursor.Skip((int)query.Skip);
            }

            return(cursor);
        }
コード例 #2
0
ファイル: PagedListExtensions.cs プロジェクト: xlgwr/osdr
        public async static Task <PagedList <TProjection> > ToPagedListAsync <TProjection>(this IAggregateFluent <TProjection> findFluent, int pageNumber, int pageSize)
        {
            var count = await findFluent.AnyAsync() ? findFluent.Group(new BsonDocument
            {
                { "_id", "_id" },
                { "count", new BsonDocument("$sum", 1) }
            })
                        .FirstAsync().Result["count"].AsInt32 : 0;

            var items = await findFluent.Skip(pageSize *(pageNumber - 1))
                        .Limit(pageSize)
                        .ToListAsync();

            return(new PagedList <TProjection>(items, count, pageNumber, pageSize));
        }
コード例 #3
0
        public static IAggregateFluent <Disease> Sample(IAggregateFluent <Disease> agg, int count)
        {
            var new_agg = agg.Skip(10);
            var stage   = new_agg.Stages[new_agg.Stages.Count - 1];
            var newDoc  = new BsonDocument {
                { "$sample", new BsonDocument {
                      { "size", count }
                  } }
            };

            stage.GetType().GetField("_document"
                                     , BindingFlags.Instance | BindingFlags.NonPublic)
            .SetValue(stage, newDoc);
            return(new_agg);
        }
コード例 #4
0
        private PagedList <TProjection> PagedList <TProjection>(IAggregateFluent <TProjection> findFluent, int pageNumber, int pageSize)
        {
            var count = findFluent.Any() ? findFluent.Group(new BsonDocument
            {
                { "_id", "_id" },
                { "count", new BsonDocument("$sum", 1) }
            })
                        .FirstAsync().Result["count"].AsInt32 : 0;

            var items = findFluent.Skip(pageSize * (pageNumber - 1))
                        .Limit(pageSize)
                        .ToList();

            return(new PagedList <TProjection>(items, count, pageNumber, pageSize));
        }
コード例 #5
0
ファイル: PagedList.cs プロジェクト: llenroc/elazystore
        public PagedList(IAggregateFluent <T> source, int pageIndex, int pageSize)
        {
            var range = source.Skip(pageIndex * pageSize).Limit(pageSize + 1).ToList();
            int total = range.Count > pageSize ? range.Count : pageSize;

            this.TotalCount = total;
            this.TotalPages = total / pageSize;

            if (total % pageSize > 0)
            {
                TotalPages++;
            }

            this.PageSize  = pageSize;
            this.PageIndex = pageIndex;
            this.AddRange(range.Take(pageSize));
        }
コード例 #6
0
        /// <summary>
        /// Appends a match stage to the pipeline.
        /// </summary>
        /// <remarks>
        /// Taken from the post on StackTrace @ https://stackoverflow.com/questions/45530988/mongodb-using-sample-with-c-sharp-driver
        /// </remarks>
        /// <typeparam name="TResult">The type of the result.</typeparam>
        /// <param name="aggregate">The aggregate.</param>
        /// <param name="count">The sample count to retrieve.</param>
        /// <returns>
        /// The fluent aggregate interface.
        /// </returns>
        public static IAggregateFluent <TResult> Sample <TResult>(this IAggregateFluent <TResult> aggregate, int count)
        {
            Ensure.IsNotNull(aggregate, nameof(aggregate));
            var new_agg = aggregate.Skip(10);
            var stage   = new_agg.Stages[new_agg.Stages.Count - 1];
            var newDoc  = new MongoDB.Bson.BsonDocument {
                { "$sample", new MongoDB.Bson.BsonDocument {
                      { "size", count }
                  } }
            };

            stage.GetType().GetField("_document"
                                     , BindingFlags.Instance | BindingFlags.NonPublic)
            .SetValue(stage, newDoc);

            return(new_agg);
        }
コード例 #7
0
        public List <TResult> Aggregate <TResult, TID>(FilterDefinition <TEntity> filter, Expression <Func <TEntity, TID> > id, Expression <Func <IGrouping <TID, TEntity>, TResult> > group, Expression <Func <TEntity, object> > sortExp = null, SortType sortType = 0, int limit = 0, int skip = 0, ReadPreference readPreference = null)
        {
            if (filter == null)
            {
                filter = Filter.Empty;
            }
            IAggregateFluent <TResult> fluent2 = IAggregateFluentExtensions.Group(CreateAggregate(filter, CreateSortDefinition(sortExp, sortType), readPreference), id, group);

            if (skip > 0)
            {
                fluent2 = fluent2.Skip(skip);
            }
            if (limit > 0)
            {
                fluent2 = fluent2.Limit(limit);
            }
            return(IAsyncCursorSourceExtensions.ToList(fluent2));
        }
コード例 #8
0
        public List <object> SkipTake <T>(IAggregateFluent <T> result, int skip, int take, out long total)
        {
            if (take > 0)
            {
                //var sortStage = result.Stages.FirstOrDefault(x => x.OperatorName == "$sort");
                //var stages = result.Stages.Where(x => x.OperatorName != "$sort");
                //var resultForTotal = new PipelineStagePipelineDefinition<TDocument, T>(stages);

                total  = result.Count().FirstOrDefault()?.Count ?? 0;
                result = result.Skip(skip).Limit(take);
            }
            else
            {
                total = 0;
            }
            var list = result.ToList();

            return(list.Cast <object>().ToList());
        }
コード例 #9
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="TResult"></typeparam>
        /// <typeparam name="TID"></typeparam>
        /// <param name="filter"></param>
        /// <param name="group"></param>
        /// <param name="sortExp"></param>
        /// <param name="sortType"></param>
        /// <param name="limit"></param>
        /// <param name="skip"></param>
        /// <param name="readPreference"></param>
        /// <returns></returns>
        public Task <List <TResult> > AggregateAsync <TResult, TID>(FilterDefinition <TEntity> filter, ProjectionDefinition <TEntity, TResult> group, Expression <Func <TEntity, object> > sortExp = null, SortType sortType = SortType.Ascending, int limit = 0, int skip = 0, ReadPreference readPreference = null)
        {
            if (filter == null)
            {
                filter = Builders <TEntity> .Filter.Empty;
            }
            IAggregateFluent <TEntity> aggregateFluent  = base.CreateAggregate(filter, base.CreateSortDefinition <TEntity>(sortExp, sortType), readPreference);
            IAggregateFluent <TResult> aggregateFluent2 = aggregateFluent.Group <TResult>(group);

            if (skip > 0)
            {
                aggregateFluent2 = aggregateFluent2.Skip(skip);
            }
            if (limit > 0)
            {
                aggregateFluent2 = aggregateFluent2.Limit(limit);
            }
            return(aggregateFluent2.ToListAsync(default(CancellationToken)));
        }
コード例 #10
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="TResult"></typeparam>
        /// <typeparam name="TID"></typeparam>
        /// <param name="filter"></param>
        /// <param name="id">$group -&gt; _id</param>
        /// <param name="group">$group</param>
        /// <param name="sortExp"></param>
        /// <param name="sortType"></param>
        /// <param name="limit"></param>
        /// <param name="skip"></param>
        /// <param name="readPreference"></param>
        /// <returns></returns>
        public List <TResult> Aggregate <TResult, TID>(FilterDefinition <TEntity> filter, Expression <Func <TEntity, TID> > id, Expression <Func <IGrouping <TID, TEntity>, TResult> > group, Expression <Func <TEntity, object> > sortExp = null, SortType sortType = SortType.Ascending, int limit = 0, int skip = 0, ReadPreference readPreference = null)
        {
            if (filter == null)
            {
                filter = Builders <TEntity> .Filter.Empty;
            }
            IAggregateFluent <TEntity> aggregate       = base.CreateAggregate(filter, base.CreateSortDefinition <TEntity>(sortExp, sortType), readPreference);
            IAggregateFluent <TResult> aggregateFluent = aggregate.Group(id, group);

            if (skip > 0)
            {
                aggregateFluent = aggregateFluent.Skip(skip);
            }
            if (limit > 0)
            {
                aggregateFluent = aggregateFluent.Limit(limit);
            }
            return(aggregateFluent.ToList(default(CancellationToken)));
        }
コード例 #11
0
        private async Task InitializeAsync(IAggregateFluent <T> source, int pageIndex, int pageSize)
        {
            var range = source.Skip(pageIndex * pageSize).Limit(pageSize + 1).ToList();
            int total = range.Count > pageSize ? range.Count : pageSize;

            TotalCount = (await source.ToListAsync()).Count;
            if (pageSize > 0)
            {
                TotalPages = total / pageSize;
            }

            if (total % pageSize > 0)
            {
                TotalPages++;
            }

            PageSize  = pageSize;
            PageIndex = pageIndex;
            AddRange(range.Take(pageSize));
        }
コード例 #12
0
        public PagedList(IAggregateFluent <T> source, int pageIndex, int pageSize)
        {
            var range = source.Skip(pageIndex * pageSize).Limit(pageSize + 1).ToList();
            int total = range.Count > pageSize ? range.Count : pageSize;

            TotalCount = source.ToListAsync().Result.Count;
            if (pageSize > 0)
            {
                TotalPages = total / pageSize;
            }

            if (total % pageSize > 0)
            {
                TotalPages++;
            }

            PageSize  = pageSize;
            PageIndex = pageIndex;
            AddRange(range.Take(pageSize));
        }
コード例 #13
0
        public Task <List <TProjection> > AggregateAsync <TProjection>(Expression <Func <TEntity, bool> > filterExp, ProjectionDefinition <TEntity, TProjection> group, Expression <Func <TEntity, object> > sortExp = null, SortType sortType = SortType.Ascending, int limit = 0, int skip = 0, ReadPreference readPreference = null)
        {
            FilterDefinition <TEntity> filter = null;

            if (filterExp != null)
            {
                filter = Filter.Where(filterExp);
            }
            else
            {
                filter = Filter.Empty;
            }
            IAggregateFluent <TProjection> fluent2 = CreateAggregate(filterExp, CreateSortDefinition(sortExp, sortType), readPreference).Group(group);

            if (skip > 0)
            {
                fluent2 = fluent2.Skip(skip);
            }
            if (limit > 0)
            {
                fluent2 = fluent2.Limit(limit);
            }
            return(IAsyncCursorSourceExtensions.ToListAsync(fluent2));
        }
コード例 #14
0
 public IMongoPagingContainer <TEntity> Skip(int skip)
 {
     return(new AggregateFluentPagingContainer <TEntity>(_source.Skip(skip)));
 }
コード例 #15
0
        public IDocumentAggregateCursor <TResult> Skip(int skip)
        {
            var next = _fluentAggregateCursor.Skip(skip);

            return(CreateNextStage(next));
        }
コード例 #16
0
        /// <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
                       ));
        }
コード例 #17
0
        /// <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
                       ));
        }