Пример #1
0
        private static bool IsValid <T>(IFindFluent <T, T> records, int pageIndex, int pageSize)
        {
            var countOfRecords = records.CountDocuments();
            var maxPageIndex   = GetMaxPageIndex(countOfRecords, pageSize);

            return(pageIndex >= 1 && pageIndex <= maxPageIndex);
        }
Пример #2
0
        /// <summary>
        /// 分页
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="orderedResult">已排序集合对象</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页容量</param>
        /// <returns>实体对象列表</returns>
        public static Page <T> ToPage <T>(this IFindFluent <T, T> orderedResult, int pageIndex, int pageSize)
        {
            int       rowCount    = (int)orderedResult.CountDocuments();
            int       pageCount   = (int)Math.Ceiling(rowCount * 1.0 / pageSize);
            IList <T> pagedResult = orderedResult.Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList();

            return(new Page <T>(pagedResult, pageIndex, pageSize, pageCount, rowCount));
        }
Пример #3
0
        private bool ProceedFoundedInfo <T>(out T userData, IFindFluent <T, T> foundedUsers)
        {
            using var foundedUserStream = foundedUsers.ToCursor();

            foundedUserStream.MoveNext();

            userData = foundedUserStream.Current.FirstOrDefault();

            return(foundedUsers.CountDocuments() != 0);
        }
        public List <User> GetUsers()
        {
            IFindFluent <User, User> findFluent = userCollection.Find(new BsonDocument());

            if (findFluent.CountDocuments() == 0)
            {
                return(new List <User>());
            }
            return(findFluent.ToList());
        }
        public User login(string username, string password)
        {
            var filter = Builders <User> .Filter.And(Builders <User> .Filter.Eq("username", username), Builders <User> .Filter.Eq("password", password));

            IFindFluent <User, User> findFluent = userCollection.Find(filter);

            if (findFluent.CountDocuments() != 0)
            {
                return(findFluent.First());
            }
            return(null);
        }
Пример #6
0
        public (List <T> result, PageModel pageModel) Paging(FilterDefinition <T> filterDefinition, SortDefinition <T> sortDefinition, int pageIndex, int pageSize, int skip, int take)
        {
            IFindFluent <T, T> find = Collection.Find(filterDefinition);

            if (sortDefinition != null)
            {
                find = find.Sort(sortDefinition);
            }
            var      pageModel = new PageModel(pageIndex, pageSize, Convert.ToInt32(find.CountDocuments()));
            List <T> result    = find.Skip(skip).Limit(take).ToList();

            return(result, pageModel);
        }
Пример #7
0
        public static ServerEconomy getEconomy()
        {
            IFindFluent <ServerEconomy, ServerEconomy> find = findEconomy(e => true);

            if (find.CountDocuments() == 0)
            {
                IMongoCollection <ServerEconomy> col = GetEconCollection();
                ServerEconomy econ = new ServerEconomy();
                col.InsertOne(econ);
                return(econ);
            }
            return(find.First());
        }
Пример #8
0
        public static dynamic count(IFindFluent <BsonDocument, BsonDocument> fluent)
        {
            var application = State.Application;
            var state       = State.Get();

            return(Tool.CreatePromise((resolve, reject) => {
                try {
                    int result = (int)fluent.CountDocuments();
                    application.AddCallback(resolve, result, state);
                } catch (Exception e) {
                    application.AddCallback(reject, $"{e.Message}", state);
                }
            }));
        }
Пример #9
0
        public T GetItemWithLatestRevision(string id)
        {
            T result = default(T);

            BsonDocument filter = new BsonDocument()
            {
                { "id", id },
            };

            //List<T> allRevisionItems = _db.GetCollection<T>(_collectionName).Find(filter).ToList();

            IFindFluent <T, T> allRevisions = _db.GetCollection <T>(_collectionName).Find(filter);

            if (allRevisions.CountDocuments() > 0)
            {
                result = allRevisions.Sort("{ 'revision.revisionNumber': -1}").First <T>();
            }
            return(result);
        }
Пример #10
0
        public T GetItemWithLatestRevisionInBranch(string id, string branch = "main")
        {
            T result = default(T);

            BsonDocument filter = new BsonDocument()
            {
                { "id", id },
                { "revision.branch", branch }
            };

            IFindFluent <T, T> allRevisions = _db.GetCollection <T>(_collectionName).Find(filter);

            if (allRevisions.CountDocuments() > 0)
            {
                result = allRevisions.Sort("{ 'revision.revisionNumber': -1}").First <T>();
            }

            return(result);
        }
Пример #11
0
        public List <Tdb> GetPagedResults(FilterDefinition <Tdb> primaryFilters, RepositoryPaging paging)
        {
            SetPaging(paging);

            FilterDefinition <Tdb> totalFilter = PreparePagingFilter(primaryFilters, paging);

            IFindFluent <Tdb, Tdb> filtered = Collection.Find(totalFilter);

            paging.TotalItems = filtered.CountDocuments();

            var sort = SetSorting(paging);

            filtered = filtered.Sort(sort);

            // runs over cursor in MongoDb
            List <Tdb> items = filtered.Skip((paging.CurrentPage - 1) * paging.PageSize).Limit(paging.PageSize).ToList();

            return(items);
        }
Пример #12
0
        public IActionResult GetNewHires(int page, string pageSize, string search)
        {
            var client          = new MongoClient(mongoDbConnection);
            var db              = client.GetDatabase("orientation");
            var mongoCollection = db.GetCollection <BsonDocument>("new-hires");

            var builder = Builders <BsonDocument> .Filter;
            // ^ - For Starts with
            // . - any character
            // * - for any number of previous "."
            var filter = builder.Regex("name", $"^{search}.*") | builder.Regex("email", $".*{search}.*") | builder.Regex("empNo", $".*{search}.*") | builder.Regex("category", $".*{search}.*");

            var projection1 = Builders <BsonDocument> .Projection.Exclude("categoryWithDeck.files");

            IFindFluent <BsonDocument, BsonDocument> query = null;

            if (!string.IsNullOrWhiteSpace(search))
            {
                query = mongoCollection.Find(filter).Project(projection1);
            }
            else
            {
                query = mongoCollection.Find(new BsonDocument()).Project(projection1);
            }

            var total = query.CountDocuments();
            var pSize = 0;

            if (pageSize == "ALL")
            {
                pSize = 1000;
            }
            else
            {
                pSize = Convert.ToInt32(pageSize);
            }
            var skip            = (page - 1) * pSize;
            var totalPage       = (total + pSize - 1) / pSize;
            var result          = query.Skip(skip).Limit(pSize).ToList();
            var convertedResult = result.ConvertAll(BsonTypeMapper.MapToDotNetValue);

            return(Ok(new { total, result = convertedResult, totalPage }));
        }
Пример #13
0
        public static guildData getGuildData(ulong id, bool create = true)
        {
            IFindFluent <guildData, guildData> find = findGuildData(id);

            if (find.CountDocuments() < 1)
            {
                if (create)
                {
                    guildData output = new guildData(id);
                    addGuildData(output);
                    return(output);
                }
                else
                {
                    throw new Exception("Guild data not found");
                }
            }
            else
            {
                return(find.First());
            }
        }
        /// <summary>
        /// 分页拓展
        /// </summary>
        /// <typeparam name="TDocument"></typeparam>
        /// <typeparam name="TNewProjection"></typeparam>
        /// <param name="entities"></param>
        /// <param name="projection"></param>
        /// <param name="pageIndex">页码,必须大于0</param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public static MongoDBPagedList <TNewProjection> ToPagedList <TDocument, TNewProjection>(this IFindFluent <TDocument, TDocument> entities, Expression <Func <TDocument, TNewProjection> > projection, int pageIndex = 1, int pageSize = 20)
        {
            if (pageIndex <= 0)
            {
                throw new InvalidOperationException($"{nameof(pageIndex)} must be a positive integer greater than 0.");
            }

            var totalCount = entities.CountDocuments();
            var items      = entities.Skip((pageIndex - 1) * pageSize).Limit(pageSize).Project(projection).ToEnumerable();
            var totalPages = (int)Math.Ceiling(totalCount / (double)pageSize);

            return(new MongoDBPagedList <TNewProjection>
            {
                PageIndex = pageIndex,
                PageSize = pageSize,
                Items = items,
                TotalCount = (int)totalCount,
                TotalPages = totalPages,
                HasNextPages = pageIndex < totalPages,
                HasPrevPages = pageIndex - 1 > 0
            });
        }
Пример #15
0
        public Book GetBook(string _id)
        {
            ObjectId Object_id;

            if (!ObjectId.TryParse(_id, out Object_id))
            {
                return(null);
            }

            IFindFluent <Book, Book> book = collection.Find(new BsonDocument {
                { "_id", Object_id }
            });

            if (book.CountDocuments() > 0)
            {
                return(book.Single());
            }
            else
            {
                return(null);
            }
        }