Esempio n. 1
0
        public static SortDefinition <MongoContentEntity> BuildSort(ODataUriParser query, Schema schema)
        {
            var orderBy = query.ParseOrderBy();

            if (orderBy != null)
            {
                var sorts = new List <SortDefinition <MongoContentEntity> >();

                while (orderBy != null)
                {
                    sorts.Add(OrderBy(orderBy, schema));

                    orderBy = orderBy.ThenBy;
                }

                if (sorts.Count > 1)
                {
                    return(Sort.Combine(sorts));
                }
                else
                {
                    return(sorts[0]);
                }
            }
            else
            {
                return(Sort.Descending(x => x.LastModified));
            }
        }
Esempio n. 2
0
        public DbQuery <TEntity> Descending(Expression <Func <TEntity, object> > expression)
        {
            if (SortDefenition == null)
            {
                SortDefenition = _sortBuilder.Descending(expression);
            }
            else
            {
                SortDefenition = _sortBuilder.Combine(SortDefenition, _sortBuilder.Descending(expression));
            }

            return(this);
        }
Esempio n. 3
0
        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);
        }
Esempio n. 4
0
        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表达式");
            }
        }
Esempio n. 5
0
        /// <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);
        }
Esempio n. 6
0
        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);
        }
        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);
        }
Esempio n. 8
0
        /// <summary>
        /// Translates the Telerik SortDescriptor to the Mongo SortDefinition
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        /// <param name="sortBuilder"></param>
        /// <returns></returns>
        private static SortDefinition <T> GetSortDefinition <T>(DataSourceRequest request, SortDefinitionBuilder <T> sortBuilder)
        {
            SortDefinition <T> sort = null;

            if (request.Sorts.Any())
            {
                // TODO: Support multiple sort statements
                foreach (SortDescriptor sortDescriptor in request.Sorts)
                {
                    if (sortDescriptor.SortDirection == ListSortDirection.Ascending)
                    {
                        sort = sortBuilder.Ascending(sortDescriptor.Member);
                    }
                    else
                    {
                        sort = sortBuilder.Descending(sortDescriptor.Member);
                    }
                    break;
                }
            }
            else
            {
                // Might not need a default sort... I used it though for paging on the default mongo _Id
                // TODO: Enhance or paramterise this
                sort = Builders <T> .Sort.Ascending("_id");
            }

            return(sort);
        }
Esempio n. 9
0
        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));
        }
Esempio n. 10
0
        public List <T> GetPageDesc(Expression <Func <T, bool> > criteria, Expression <Func <T, object> > descSort, QueryParams pParams)
        {
            var sort   = new SortDefinitionBuilder <T>();
            var result = _collection.Find(criteria).Sort(sort.Descending(descSort)).Skip((pParams.Index - 1) * pParams.Size).Limit(
                pParams.Size).ToList();

            return(result);
        }
Esempio n. 11
0
        async void HandleGet(string data, string id)
        {

            if (data.Length < 7)
            {
                Console.WriteLine("get input was too short at" + data.Length);
                return;
            }

            var builder = Builders<listing>.Filter;


            string thenby = sortBy.players.ToString(); //set second sort by initially to sort secondarily to current num of players...
            //if we're actually requested to sort by that already, sort secondarily by max players instead
            if (data[6] == sortBy.players)
            {
                thenby = sortBy.max.ToString();
            }

            //sanity check input of requested sort type to avoid some null reference exceptions
            if (listing.dummy.GetType().GetField(data[6].ToString()) == null || listing.dummy.GetType().GetField(thenby) == null)
            {
                //invalid sort request input from user
                //throw new ArgumentOutOfRangeException();

                Console.WriteLine("invalid sort type requested: " + data[6].ToString());
                return;
            }

            List<listing> membersList =
             await
                 games.Find(new BsonDocument())
                     .Sort(sort.Descending(data[6].ToString()))
                     .Sort(sort.Descending(thenby))
                     .Limit(Program.numReturns)
                     .ToListAsync();



            Console.WriteLine("found " + membersList.Count + " games");

            Send(
                mmcodes.get.ToString() + String.Join(delimeters.slistingGroups, membersList) //send each listing separated by delimeter, each listing being converted to string
                );

        } //end HandleGet
Esempio n. 12
0
        /// <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 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);
        }
        private static SortDefinition <T> CreateODataSort <T>(IODataQuery query, bool check = false)
        {
            var orderby = query.Order;

            SortDefinitionBuilder <T> sortBuilder           = Builders <T> .Sort;
            SortDefinition <T>        sortDefinition        = null;
            SortDefinition <T>        defaultSortDefinition = sortBuilder.Descending("CreateDate");

            if (String.IsNullOrEmpty(orderby))
            {
                return(defaultSortDefinition);
            }

            var sections = orderby.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var section in sections)
            {
                var order     = section.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                var field     = order.FirstOrDefault();
                var direction = "asc";

                if (check && !typeof(T).HasField(field))
                {
                    continue;
                }

                if (order.LastOrDefault().ToLower() == "desc")
                {
                    direction = "desc";
                }

                if (sortDefinition == null)
                {
                    sortDefinition = direction == "asc"
                        ? sortBuilder.Ascending(field)
                        : sortBuilder.Descending(field);
                }

                sortDefinition = direction == "asc"
                    ? sortDefinition.Ascending(field)
                    : sortDefinition.Descending(field);
            }

            return(sortDefinition ?? defaultSortDefinition);
        }
Esempio n. 15
0
        public async Task <List <DeviceStateHistory> > GetDeviceStateHistory(Guid deviceId, int days = 30)
        {
            DateTime startDateUtc = DateTime.UtcNow.AddDays((-1 * days));

            FilterDefinition <DeviceStateHistory> filter = filterBuilder.Eq(d => d.DeviceId, deviceId)
                                                           & filterBuilder.Gte(d => d.Timestamp, startDateUtc);
            SortDefinition <DeviceStateHistory> sort = sortBuilder.Descending(d => d.Version);

            return(await deviceHistoryCollection.Find(filter).Sort(sort).ToListAsync());
        }
Esempio n. 16
0
        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());
        }
Esempio n. 17
0
        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);
        }
        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());
        }
Esempio n. 19
0
        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));
        }
Esempio n. 20
0
        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);
        }
        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());
        }
        private async Task <List <Article> > GetArticlesByfilter(FilterDefinition <Article> filter, int pageSize)
        {
            SortDefinitionBuilder <Article> builderSort = Builders <Article> .Sort;
            var sort    = builderSort.Descending("_id");
            var options = new FindOptions <Article, Article>()
            {
                Sort  = sort,
                Limit = pageSize
            };
            var cursor = await this._collection.FindAsync(filter, options);

            return(await cursor.ToListAsync());
        }
Esempio n. 23
0
        public async Task <List <Comment> > GetCommentByPostId(string postId)
        {
            var filter = Builders <Comment> .Filter.Eq("PostId", postId);

            SortDefinitionBuilder <Comment> builderSort = Builders <Comment> .Sort;
            var sort    = builderSort.Descending("_id");
            var options = new FindOptions <Comment, Comment>()
            {
                Sort = sort,
            };
            var cursor = await this._collection.FindAsync(filter, options);

            return(await cursor.ToListAsync());
        }
        /// <summary>
        /// 根据条件,返回文档集合
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <param name="filter"></param>
        /// <param name="orderByPropertyName"></param>
        /// <param name="isDescending"></param>
        /// <returns></returns>
        public virtual async Task <List <T> > SelectAsync(FilterDefinition <T> filter, string orderByPropertyName, bool isDescending = true)
        {
            var fluent = Collection.Find(filter);

            if (string.IsNullOrWhiteSpace(orderByPropertyName))
            {
                return(await fluent.ToListAsync());
            }

            var sortDefinitionBuilder = new SortDefinitionBuilder <T>();
            var sort = isDescending ? sortDefinitionBuilder.Descending(orderByPropertyName) : sortDefinitionBuilder.Ascending(orderByPropertyName);

            return(await fluent.Sort(sort).ToListAsync());
        }
        protected virtual async Task <IEnumerable <object> > GetCollection(Expression <Func <T, bool> > filter,
                                                                           PagingSettings paging,
                                                                           IEnumerable <SortingField> sortings,
                                                                           Expression <Func <T, object> > projection,
                                                                           CancellationToken token = default(CancellationToken))
        {
            if (!CollectionExist)
            {
                return(new List <object>());
            }
            try
            {
                var collection = filter == null?Collection.Find(_ => true) : Collection.Find(filter);

                var sortingBuilder = new SortDefinitionBuilder <T>();
                var sorts          = new List <SortDefinition <T> >();
                if (sortings != null)
                {
                    sorts.AddRange(from sf in sortings
                                   where !sf.IsNull
                                   select sf.SortingMode == SortingModes.Ascending
                            ? sortingBuilder.Ascending(sf.FieldName)
                            : sortingBuilder.Descending(sf.FieldName));
                }
                collection.Sort(sortingBuilder.Combine(sorts));
                if (projection != null)
                {
                    collection.Project(projection);
                }
                if (paging == null)
                {
                    return((IEnumerable <object>) await collection.ToListAsync(CancellationToken.None));
                }
                if (paging.Skip != null)
                {
                    collection = collection.Skip(paging.Skip);
                }
                if (paging.Limit != null)
                {
                    collection = collection.Limit(paging.Limit);
                }

                return((IEnumerable <object>) await collection.ToListAsync(token));
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
Esempio n. 26
0
        public IPageList <T> Query <T>(FilterCondition filter) where T : IBaseObject
        {
            this.CheckType <T>();
            IMongoCollection <T>        collection       = this.GetCollection <T>();
            FilterDefinitionBuilder <T> filter2          = Builders <T> .Filter;
            SortDefinitionBuilder <T>   sort             = Builders <T> .Sort;
            FilterDefinition <T>        filterDefinition = filter2.Empty;

            foreach (FilterValue current in filter.Fields)
            {
                switch (current.FilterType)
                {
                case FilterType.LTE:
                    filterDefinition &= filter2.Lte <object>(current.FieldName, current.Value);
                    break;

                case FilterType.GTE:
                    filterDefinition &= filter2.Gte <object>(current.FieldName, current.Value);
                    break;

                case FilterType.LT:
                    filterDefinition &= filter2.Lt <object>(current.FieldName, current.Value);
                    break;

                case FilterType.GT:
                    filterDefinition &= filter2.Gt <object>(current.FieldName, current.Value);
                    break;

                case FilterType.EQ:
                    goto IL_12E;

                case FilterType.Like:
                    filterDefinition &= filter2.Regex(current.FieldName, new Regex(current.Value.ToString(), RegexOptions.IgnoreCase));
                    break;

                default:
                    goto IL_12E;
                }
                continue;
IL_12E:
                filterDefinition &= filter2.Eq <object>(current.FieldName, current.Value);
            }
            Task <long>        task  = collection.CountAsync(filterDefinition, null, default(CancellationToken));
            SortDefinition <T> sort2 = (filter.Direction == OrderDirection.DESC) ? sort.Descending(filter.OrderBy) : sort.Ascending(filter.OrderBy);
            Task <List <T> >   task2 = collection.Find(filterDefinition, null).Sort(sort2).Limit(new int?(filter.PageSize)).Skip(new int?((filter.PageIndex - 1) * filter.PageSize)).ToListAsync(default(CancellationToken));

            return(new PageList <T>(task2.Result, filter.PageIndex, filter.PageSize, (int)task.Result));
        }
Esempio n. 27
0
        public virtual async Task <IEnumerable <T> > GetAsync(
            Expression <Func <T, bool> > filter,
            PagingOptions pagingOptions,
            IList <SortingOptions> sortingOptions,
            CancellationToken token)
        {
            try
            {
                if (!this.IsCollectionsExists)
                {
                    return(Enumerable.Empty <T>());
                }

                var sortDefinitionBuilder = new SortDefinitionBuilder <T>();
                var sortDefinitions       = new List <SortDefinition <T> >();

                if (sortingOptions.Any())
                {
                    sortDefinitions.AddRange(
                        sortingOptions.Select(
                            sortingOption => sortingOption.SortingMode == SortingMode.Ascending
                                                 ? sortDefinitionBuilder.Ascending(sortingOption.FieldName)
                                                 : sortDefinitionBuilder.Descending(sortingOption.FieldName)));
                }

                var sourceCollection = filter == null?Collection.Find(_ => true) : Collection.Find(filter);

                sourceCollection.Sort(sortDefinitionBuilder.Combine(sortDefinitions));

                if (pagingOptions != null && pagingOptions.Skip != null)
                {
                    sourceCollection = sourceCollection.Skip(pagingOptions.Skip);
                }

                if (pagingOptions != null && pagingOptions.Limit != null)
                {
                    sourceCollection = sourceCollection.Limit(pagingOptions.Limit);
                }

                return(await sourceCollection.ToListAsync(token));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Esempio n. 28
0
        /// <summary>
        /// 初始化排序条件  主要当条件为空时 会默认以ObjectId递增的一个排序
        /// </summary>
        /// <param name="sortBy"></param>
        /// <returns></returns>
        private SortDefinition <BsonDocument> InitSortBy(string sortBy, params string[] fields)
        {
            SortDefinitionBuilder <BsonDocument> sortBuilder = Builders <BsonDocument> .Sort;
            SortDefinition <BsonDocument>        sortFilter  = null;

            if (sortBy == null)
            {
                //默认ObjectId 递增
                sortFilter = Builders <BsonDocument> .Sort.Descending(OBJECTID_KEY); // new BsonDocument(OBJECTID_KEY, 1);
            }
            else
            {
                if (sortBy.ToLower() == "asc")
                {
                    foreach (var item in fields)
                    {
                        if (sortFilter == null)
                        {
                            sortFilter = sortBuilder.Ascending(item);
                        }
                        else
                        {
                            sortFilter = sortFilter.Ascending(item);
                        }
                    }
                }
                else if (sortBy.ToLower() == "desc")
                {
                    foreach (var item in fields)
                    {
                        if (sortFilter == null)
                        {
                            sortFilter = sortBuilder.Descending(item);
                        }
                        else
                        {
                            sortFilter = sortFilter.Descending(item);
                        }
                    }
                }
                else
                {
                    sortFilter = sortFilter.Descending(OBJECTID_KEY);
                }
            }
            return(sortFilter);
        }
Esempio n. 29
0
        public Puzzle GetOneRandomly(List <int> excludedIds, string variant, int?userId, double nearRating = 1500)
        {
            FilterDefinitionBuilder <Puzzle> filterBuilder = Builders <Puzzle> .Filter;
            FilterDefinition <Puzzle>        filter        = filterBuilder.Nin("_id", excludedIds) & filterBuilder.Eq("inReview", false)
                                                             & filterBuilder.Eq("approved", true);

            if (variant != "Mixed")
            {
                filter &= filterBuilder.Eq("variant", variant);
            }
            if (userId.HasValue)
            {
                filter &= filterBuilder.Ne("author", userId.Value) & filterBuilder.Nin("reviewers", new int[] { userId.Value });
            }
            FilterDefinition <Puzzle> lteFilter = filter;
            FilterDefinition <Puzzle> gtFilter  = filter;
            bool higherRated = RandomBoolean();

            gtFilter  &= filterBuilder.Gt("rating.value", nearRating);
            lteFilter &= filterBuilder.Lte("rating.value", nearRating);
            var foundGt  = puzzleCollection.Find(gtFilter);
            var foundLte = puzzleCollection.Find(lteFilter);

            if (foundGt == null && foundLte == null)
            {
                return(null);
            }
            SortDefinitionBuilder <Puzzle> sortBuilder = Builders <Puzzle> .Sort;

            foundGt  = foundGt.Sort(sortBuilder.Ascending("rating.value")).Limit(1);
            foundLte = foundLte.Sort(sortBuilder.Descending("rating.value")).Limit(1);
            Puzzle oneGt  = foundGt.FirstOrDefault();
            Puzzle oneLte = foundLte.FirstOrDefault();

            if (oneGt == null)
            {
                return(oneLte);
            }
            else if (oneLte == null)
            {
                return(oneGt);
            }
            else
            {
                return(RandomBoolean() ? oneGt : oneLte);
            }
        }
Esempio n. 30
0
        public SortDefinition <BsonDocument> GetSortDefinitionBySortFields(int metaObjectId, SortField[] sortFields)
        {
            var builder = new SortDefinitionBuilder <BsonDocument>();

            if (sortFields == null || !sortFields.Any())
            {
                //默认给更新时间倒序排列
                sortFields = new[] { new SortField {
                                         Column = "ModifyTime", IsDesc = true
                                     } };
            }
            //获取全部字段
            var metaFieldDic = GetMetaFieldDicUnDeleted(metaObjectId);
            SortDefinition <BsonDocument> sort = null;

            foreach (var item in sortFields)
            {
                if (!metaFieldDic.ContainsKey(item.Column))
                {
                    throw new ArgumentNullException(item.Column, $"field of {item.Column} is not exist in current MetaObject");
                }
                if (item.IsDesc)
                {
                    if (sort == null)
                    {
                        sort = builder.Descending(item.Column);
                    }
                    else
                    {
                        sort = sort.Descending(item.Column);
                    }
                }
                else
                {
                    if (sort == null)
                    {
                        sort = builder.Ascending(item.Column);
                    }
                    else
                    {
                        sort = sort.Ascending(item.Column);
                    }
                }
            }
            return(sort);
        }