Beispiel #1
0
        /// <summary>
        /// 获取数据列表
        /// </summary>
        /// <typeparam name="T">数据类型</typeparam>
        /// <param name="DbName">数据库名称</param>
        /// <param name="TableName">表名</param>
        /// <param name="where">查询条件</param>
        /// <param name="orderby">排序</param>
        /// <param name="fields">返回字段</param>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">分页大小</param>
        /// <param name="count">记录总数</param>
        /// <returns>数据列表</returns>
        public static List <T> GetPaged <T>(string DbName, string TableName, BsonDocument where, string[] orderby, BsonDocument fields, int pageIndex, int pageSize)
        {
            List <T> list = new List <T>();

            try
            {
                MongoDatabase db = mongo.GetDatabase(DbName);//数据库名字
                if (db == null)
                {
                    throw new ArgumentNullException("db not found.");
                }
                MongoCollection <BsonDocument> categories = db.GetCollection <BsonDocument>(TableName);//表的名字
                MongoCursor <T> cursor = categories.FindAs <T>(new QueryComplete(where));
                cursor.SetSkip(((pageIndex - 1) * pageSize));
                cursor.SetLimit(pageSize);
                cursor.SetSortOrder(SortBy.Descending(orderby));
                foreach (T t in cursor)
                {
                    list.Add(t);
                }
            }
            catch (Exception ex)
            {
                LogService.Write(ex);
            }
            return(list);
        }
        public BillingPlanStatsModel Plans()
        {
            MongoCursor <Organization> query = ((OrganizationRepository)_organizationRepository).Collection.FindAll()
                                               .SetFields(OrganizationRepository.FieldNames.PlanId, OrganizationRepository.FieldNames.BillingPrice, OrganizationRepository.FieldNames.BillingStatus);

            List <Organization> results = query.SetSortOrder(SortBy.Descending(OrganizationRepository.FieldNames.PlanId)).ToList();

            List <Organization> smallOrganizations  = results.Where(o => String.Equals(o.PlanId, BillingManager.SmallPlan.Id) && o.BillingPrice > 0).ToList();
            List <Organization> mediumOrganizations = results.Where(o => String.Equals(o.PlanId, BillingManager.MediumPlan.Id) && o.BillingPrice > 0).ToList();
            List <Organization> largeOrganizations  = results.Where(o => String.Equals(o.PlanId, BillingManager.LargePlan.Id) && o.BillingPrice > 0).ToList();
            decimal             monthlyTotalPaid    = smallOrganizations.Sum(o => o.BillingPrice) + mediumOrganizations.Sum(o => o.BillingPrice) + largeOrganizations.Sum(o => o.BillingPrice);

            List <Organization> smallYearlyOrganizations  = results.Where(o => String.Equals(o.PlanId, BillingManager.SmallYearlyPlan.Id) && o.BillingPrice > 0).ToList();
            List <Organization> mediumYearlyOrganizations = results.Where(o => String.Equals(o.PlanId, BillingManager.MediumYearlyPlan.Id) && o.BillingPrice > 0).ToList();
            List <Organization> largeYearlyOrganizations  = results.Where(o => String.Equals(o.PlanId, BillingManager.LargeYearlyPlan.Id) && o.BillingPrice > 0).ToList();
            decimal             yearlyTotalPaid           = smallYearlyOrganizations.Sum(o => o.BillingPrice) + mediumYearlyOrganizations.Sum(o => o.BillingPrice) + largeYearlyOrganizations.Sum(o => o.BillingPrice);

            return(new BillingPlanStatsModel {
                SmallTotal = smallOrganizations.Count,
                SmallYearlyTotal = smallYearlyOrganizations.Count,
                MediumTotal = mediumOrganizations.Count,
                MediumYearlyTotal = mediumYearlyOrganizations.Count,
                LargeTotal = largeOrganizations.Count,
                LargeYearlyTotal = largeYearlyOrganizations.Count,
                MonthlyTotal = monthlyTotalPaid + (yearlyTotalPaid / 12),
                YearlyTotal = (monthlyTotalPaid * 12) + yearlyTotalPaid,
                MonthlyTotalAccounts = smallOrganizations.Count + mediumOrganizations.Count + largeOrganizations.Count,
                YearlyTotalAccounts = smallYearlyOrganizations.Count + mediumYearlyOrganizations.Count + largeYearlyOrganizations.Count,
                FreeAccounts = results.Count(o => String.Equals(o.PlanId, BillingManager.FreePlan.Id)),
                PaidAccounts = results.Count(o => !String.Equals(o.PlanId, BillingManager.FreePlan.Id) && o.BillingPrice > 0),
                FreeloaderAccounts = results.Count(o => !String.Equals(o.PlanId, BillingManager.FreePlan.Id) && o.BillingPrice <= 0),
                SuspendedAccounts = results.Count(o => o.BillingStatus != BillingStatus.Active && o.BillingStatus != BillingStatus.Trialing),
            });
        }
Beispiel #3
0
        /// <summary>
        /// 返回mongo查询数据
        /// </summary>
        /// <typeparam name="T">数据类型</typeparam>
        /// <param name="query">查询条件</param>
        /// <param name="collectionName">表名</param>
        /// <param name="filter">过滤条件</param>
        /// <returns>mongo数据</returns>
        public MongoCursor <T> QueryCursor <T>(IMongoQuery query, string collectionName, BaseFilter filter)
        {
            MongoCollection collection = GetMongoCollection(collectionName);

            filter.RecordCount = Convert.ToInt32(collection.Count(query));
            SortByDocument  sortByDocument = GetSortFromStr(filter.OrderbyStr);
            MongoCursor <T> mongoCursor    = collection.FindAs <T>(query);

            //查询性能分析
            //BsonDocument document = collection.FindAs<T>(query).Explain();
            if (sortByDocument != null)
            {
                mongoCursor = mongoCursor.SetSortOrder(sortByDocument);
            }

            if (filter.PageSize == 0)
            {
                filter.PageSize = DefaultPageSize;
            }
            if (filter.PageNo == 0)
            {
                filter.PageNo = DefaultPageNo;
            }
            return(mongoCursor.SetSkip(filter.PageSize * (filter.PageNo - 1)).SetLimit(filter.PageSize));
        }
        public Nullable <DateTime> GetDateOfDeviceLastVisit(Guid deviceId, Guid applicationId)
        {
            try
            {
                IMongoQuery queryBase = Query.And
                                        (
                    Query <AppUsageSummary> .EQ <Guid>(mem => mem.ApplicationId, applicationId),
                    Query.EQ("DevicesVisits.DeviceId", BsonValue.Create(deviceId))
                                        );

                MongoCursor <AppUsageSummary> appUsageSummaries =
                    this.GetCollection <AppUsageSummary>().Find(queryBase);

                appUsageSummaries.SetSortOrder(SortBy <AppUsageSummary> .Descending(x => x.Date));
                AppUsageSummary appUsageSummary = appUsageSummaries.FirstOrDefault();

                if (appUsageSummary != null)
                {
                    return(appUsageSummary.Date);
                }

                return(null);
            }
            catch (Exception ex)
            {
                throw new DataAccessLayerException(ex);
            }
        }
Beispiel #5
0
 public static MongoCursor <TDocument> zFindAll <TDocument>(this MongoCollection collection, SortByWrapper sort = null, FieldsWrapper fields = null, int limit = 0, BsonDocument options = null)
 {
     MongoLog.CurrentMongoLog.LogFindAllAs(collection, sort, fields, limit, options);
     return(MongoLog.CurrentMongoLog.ExecuteAndLogResult(
                () =>
     {
         MongoCursor <TDocument> cursor = collection.FindAllAs <TDocument>();
         if (sort != null)
         {
             cursor.SetSortOrder(sort);
         }
         if (fields != null)
         {
             cursor.SetFields(fields);
         }
         if (limit != 0)
         {
             cursor.SetLimit(limit);
         }
         if (options != null)
         {
             cursor.SetOptions(options);
         }
         return cursor;
     }));
 }
Beispiel #6
0
        /// <summary>
        /// 获取列表top几
        /// </summary>
        /// <param name="sortByMap"> var sort = new SortByDocument { { "_id", -1 } }; ->这里1为ASC, -1为DESC</param>
        /// <returns></returns>
        public List <T> List(Expression <Func <T, bool> > filter, Dictionary <string, sbyte> sortByMap = null, int?top = null)
        {
            MongoCursor <T> cursor = null;

            if (null != filter)
            {
                var findQuery = Query <T> .Where(filter);

                cursor = this._mongoCollection.Find(findQuery);
            }
            else
            {
                cursor = this._mongoCollection.FindAll();
            }

            if (null != sortByMap)
            {
                var orderByQuery = new SortByDocument(sortByMap);
                cursor = cursor.SetSortOrder(orderByQuery);
            }

            if (top.HasValue)
            {
                List <T> list = cursor.SetLimit(top.Value).ToList();
                return(list);
            }
            return(cursor.ToList());
        }
Beispiel #7
0
 /// <summary>
 /// 查询后的数据排序返回list
 /// </summary>
 /// <typeparam name="Z">类型</typeparam>
 /// <param name="mongoCursor">查询出的数据</param>
 /// <param name="orderStr">排序字符</param>
 /// <returns>数据排序返回list</returns>
 public List <Z> ReturnList <Z>(MongoCursor <Z> mongoCursor, string orderStr)
 {
     if (!string.IsNullOrEmpty(orderStr))
     {
         SortByDocument sortByDocument = GetSortFromStr(orderStr);
         mongoCursor = mongoCursor.SetSortOrder();
     }
     return(mongoCursor.ToListEntity <Z>());
 }
        //
        // GET: /Cars/

        public ActionResult Index()
        {
            MongoCursor <Car> carsInDbCursor = CarRentalContext.Cars.FindAll();

            /* LINQ example
             * IEnumerable<Car> cars = carsInDbCursor.AsQueryable().Where(c => c.NumberOfDoors > 3); */
            IMongoSortBy sortByCars = SortBy <Car> .Descending(c => c.Make);

            carsInDbCursor.SetSortOrder(sortByCars);
            AggregateExamples();
            return(View(carsInDbCursor.ConvertAllToViewModels()));
        }
Beispiel #9
0
        public IList <Interaction> Get(IEnumerable <string> identifiers, string sortby)
        {
            var clauses = new List <IMongoQuery>();
            IEnumerable <BsonValue> ids = identifiers.Select(i => (BsonValue)i);

            clauses.Add(MonQ.Query.In(Field.PRIMARYKEY, ids));

            IMongoQuery query = MonQ.Query.And(clauses);
            MongoCursor <BsonDocument> cursor = collection.Find(query);

            if (sortby != null)
            {
                cursor = cursor.SetSortOrder(MonQ.SortBy.Ascending(sortby));
            }
            else
            {
                cursor = cursor.SetSortOrder(MonQ.SortBy.Descending(Field.WHEN));
            }

            return(cursor.ToInteractions().ToList());
        }
Beispiel #10
0
        private List <BsonValue> CollectSelfLinks(IMongoQuery query, IMongoSortBy sortBy)
        {
            MongoCursor <BsonDocument> cursor = _collection.Find(query);

            if (sortBy != null)
            {
                cursor.SetSortOrder(sortBy);
            }
            cursor = cursor.SetFields(InternalField.SELFLINK);

            return(cursor.Select(doc => doc.GetValue(InternalField.SELFLINK)).ToList());
        }
Beispiel #11
0
        public List <T> Page <T>(int skip, int limit, string orderBy) where T : class, new()
        {
            MongoCursor <T> cursor = mongoDb.GetCollection <T>(GetTypeName(typeof(T))).FindAll();

            cursor.SetSkip(skip).SetLimit(limit);

            if (!String.IsNullOrEmpty(orderBy))
            {
                cursor.SetSortOrder(SortBy.Descending(orderBy));
            }
            return(cursor.ToList());
        }
Beispiel #12
0
        public IEnumerable <BundleEntry> Get(IEnumerable <Uri> keys, string sortby)
        {
            Uri firstkey = keys.FirstOrDefault();

            if (firstkey == null)
            {
                yield break;
            }

            var clauses = new List <IMongoQuery>();
            IEnumerable <BsonValue> ids = keys.Select(k => (BsonValue)k.ToString());

            if (AnalyseKey(firstkey) == KeyType.History)
            {
                clauses.Add(MonQ.Query.In(Field.VERSIONID, ids));
            }
            else
            {
                clauses.Add(MonQ.Query.In(Field.ID, ids));
                clauses.Add(MonQ.Query.EQ(Field.STATE, Value.CURRENT));
            }

            IMongoQuery query = MonQ.Query.And(clauses);
            MongoCursor <BsonDocument> cursor = collection.Find(query);

            if (sortby != null)
            {
                cursor = cursor.SetSortOrder(MonQ.SortBy.Ascending(sortby));
            }
            else
            {
                cursor = cursor.SetSortOrder(MonQ.SortBy.Descending(Field.VERSIONDATE));
            }

            foreach (BsonDocument document in cursor)
            {
                BundleEntry entry = BsonToBundleEntry(document);
                yield return(entry);
            }
        }
Beispiel #13
0
        public IList <Entry> GetCurrent(IEnumerable <string> identifiers, string sortby)
        {
            var clauses = new List <IMongoQuery>();
            IEnumerable <BsonValue> ids = identifiers.Select(i => (BsonValue)i);

            clauses.Add(MonQ.Query.In(Field.REFERENCE, ids));
            clauses.Add(MonQ.Query.EQ(Field.STATE, Value.CURRENT));
            IMongoQuery query = MonQ.Query.And(clauses);

            MongoCursor <BsonDocument> cursor = collection.Find(query);

            if (sortby != null)
            {
                cursor = cursor.SetSortOrder(MonQ.SortBy.Ascending(sortby));
            }
            else
            {
                cursor = cursor.SetSortOrder(MonQ.SortBy.Descending(Field.WHEN));
            }

            return(cursor.ToEntries().ToList());
        }
Beispiel #14
0
        private MongoCursor <T> OrderCursor(MongoCursor <T> cursor, IList <string> orderByFieldAsc, IList <string> orderByFieldDesc)
        {
            bool fieldDesc = ((orderByFieldDesc != null) && (orderByFieldDesc.Count > 0));
            bool fieldAsc  = ((orderByFieldAsc != null) && (orderByFieldAsc.Count > 0));

            if ((fieldAsc) && (fieldDesc))
            {
                return(cursor.SetSortOrder(SortBy.Descending(orderByFieldDesc.ToArray()).Ascending(orderByFieldAsc.ToArray())));
            }
            else if (fieldAsc)
            {
                return(cursor.SetSortOrder(SortBy.Ascending(orderByFieldAsc.ToArray())));
            }
            else if (fieldDesc)
            {
                return(cursor.SetSortOrder(SortBy.Descending(orderByFieldDesc.ToArray())));
            }
            else
            {
                return(cursor);
            }
        }
Beispiel #15
0
        private MongoCursor <BsonDocument> Find(string collectionName, string query, string fields, string sort, int skip, int limit)
        {
            MongoCollection <BsonDocument> collection = Database.GetCollection <BsonDocument>(collectionName);
            MongoCursor <BsonDocument>     cursor     = (string.IsNullOrEmpty(query)) ? collection.FindAll() : collection.Find(new QueryDocument(ParseQuery(query)));

            if (!string.IsNullOrEmpty(fields))
            {
                ParseQuery(fields).ToList().ForEach(item =>
                {
                    if (item.Value == 0)
                    {
                        cursor.SetFields(Fields.Exclude(item.Name));
                    }
                    else
                    {
                        cursor.SetFields(Fields.Include(item.Name));
                    }
                });
            }

            if (!string.IsNullOrEmpty(sort))
            {
                ParseQuery(sort).ToList().ForEach(itemtoSort =>
                {
                    if (itemtoSort.Value > 0)
                    {
                        cursor.SetSortOrder(SortBy.Ascending(itemtoSort.Name));
                    }
                    else
                    {
                        cursor.SetSortOrder(SortBy.Descending(itemtoSort.Name));
                    }
                });
            }

            cursor.SetSkip(skip);
            cursor.SetLimit(limit);
            return(cursor);
        }
Beispiel #16
0
        public IEnumerable <AggregatedValue> Find(DateTime startDate, DateTime endDate, Dictionary <string, List <string> > props)
        {
            MongoCollection <StoredCounter> items = MongoDb.GetCollection <StoredCounter>("countersData");
            IMongoQuery   q      = Query.And(Query.GTE("date", startDate), Query.LT("date", endDate));
            FieldsBuilder fields = new FieldsBuilder();

            //fields.Include("date", "data.Max", "data.Min", "data.Count", "data.Avg", "data.Sum");
            fields.Include("date", "data");


            foreach (KeyValuePair <string, List <string> > prop in props)
            {
                string fieldName = "props." + prop.Key;
                fields.Include(fieldName);
                if (prop.Value.Count == 0)
                {
                    q = Query.And(q, Query.Exists(fieldName));
                }
                else if (prop.Value.Count == 1)
                {
                    q = Query.And(q, Query.EQ(fieldName, prop.Value.First()));
                }
                else
                {
                    q = Query.And(q, Query.In(fieldName, prop.Value.Cast <BsonString>()));
                }
            }

            MongoCursor cursor = items.Find(q);

            cursor.SetFields(fields);
            cursor.SetSortOrder(SortBy.Ascending("date"));
            Stopwatch sw    = Stopwatch.StartNew();
            var       found = cursor.Cast <object>().ToList();

            sw.Stop();
            Console.WriteLine(found.Count + " entries fetched from db in " + sw.ElapsedMilliseconds + " ms");
            sw.Restart();
            var parsed = found.Cast <StoredCounter>().Select(ParseAggregatedValue).ToList();

            sw.Stop();
            Console.WriteLine(parsed.Count + " entries parsed in " + sw.ElapsedMilliseconds + " ms");
            sw.Restart();
            var result = parsed.Compact().ToList();

            sw.Stop();
            Console.WriteLine(found.Count + " entries compacted to " + result.Count + " in " + sw.ElapsedMilliseconds + " ms");
            return(result);
        }
Beispiel #17
0
        public List <T> Page <T>(System.Linq.Expressions.Expression <Func <T, bool> > expression, int skip, int limit, string orderBy) where T : class, new()
        {
            IMongoQuery query = Query <T> .Where(expression);

            MongoCursor <T> cursor = mongoDb.GetCollection <T>(GetTypeName(typeof(T))).Find(query);

            cursor.SetSkip(skip).SetLimit(limit);

            if (!String.IsNullOrEmpty(orderBy))
            {
                cursor.SetSortOrder(SortBy.Descending(orderBy));
            }

            return(cursor.ToList());
        }
Beispiel #18
0
        /// <summary>
        /// Perform a full text query on all fields indexed as text.
        /// </summary>
        /// <returns>First 50 results</returns>
        public List <T> TextSearch <T>(string searchStr, int skip, int limit, string orderBy) where T : class, new()
        {
            MongoCursor <T> cursor = mongoDb.GetCollection <T>(GetTypeName(typeof(T))).Find(Query.Text(searchStr));

            if (skip > 0)
            {
                cursor.SetSkip(skip);
            }

            cursor.SetLimit(limit);

            if (orderBy != null)
            {
                cursor.SetSortOrder(SortBy.Descending(orderBy));
            }

            return(cursor.ToList());
        }
Beispiel #19
0
        public T Get(Expression <Func <T, bool> > filter, Dictionary <string, sbyte> sortByMap)
        {
            MongoCursor <T> cursor = null;

            if (null != filter)
            {
                var findQuery = Query <T> .Where(filter);

                cursor = this._mongoCollection.FindAs <T>(findQuery);
            }
            else
            {
                cursor = this._mongoCollection.FindAllAs <T>();
            }

            if (null != sortByMap)
            {
                var orderByQuery = new SortByDocument(sortByMap);
                cursor = cursor.SetSortOrder(orderByQuery);
            }

            return(cursor.FirstOrDefault());
        }
Beispiel #20
0
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="filterList"></param>
        /// <param name="sortByMap"> var sort = new SortByDocument { { "_id", -1 } }; ->这里1为ASC, -1为DESC</param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public List <T> PageList(List <Expression <Func <T, bool> > > filterList, Dictionary <string, sbyte> sortByMap = null, int?pageIndex = null, int?pageSize = null, string[] fields = null)
        {
            MongoCursor <T> cursor = null;

            if (null != filterList && filterList.Count > 0)
            {
                var findQueryList = (from expression in filterList where null != expression select Query <T> .Where(expression)).ToList();

                var findQuery = Query.And(findQueryList);
                cursor = this._mongoCollection.FindAs <T>(findQuery);
            }
            else
            {
                cursor = this._mongoCollection.FindAllAs <T>();
            }

            if (null != sortByMap)
            {
                var orderByQuery = new SortByDocument(sortByMap);
                cursor = cursor.SetSortOrder(orderByQuery);
            }
            if (fields != null && fields.Any())
            {
                cursor = cursor.SetFields(fields);
            }
            if (pageIndex.HasValue)
            {
                if (!pageSize.HasValue)
                {
                    pageSize = 30;
                }

                List <T> list = cursor.SetSkip((pageIndex.Value - 1) * pageSize.Value).SetLimit(pageSize.Value).ToList();
                return(list);
            }
            return(cursor.ToList());
        }
Beispiel #21
0
        public List <T> Page <T>(DbQueryParams qParams) where T : class, new()
        {
            // First query part consists of search params with specified operator between
            List <IMongoQuery> queries = new List <IMongoQuery>();

            foreach (var item in qParams.QueryParams)
            {
                queries.Add(Query.Matches(item.Key, new BsonRegularExpression(String.Format("(?:{0})", item.Value), "is")));
            }

            var query = qParams.Operator == QueryOperator.AND ? Query.And(queries) : Query.Or(queries);

            MongoCursor <T> cursor = mongoDb.GetCollection <T>(GetTypeName(typeof(T))).Find(query);

            cursor.SetSkip(qParams.SkipRecords).SetLimit(qParams.Count);

            // Setting the Sort params
            if (qParams.SortParams != null && qParams.SortParams.Count > 0)
            {
                SortByBuilder sbb = new SortByBuilder();
                foreach (KeyValuePair <string, bool> sortItem in qParams.SortParams)
                {
                    if (sortItem.Value)
                    {
                        sbb.Ascending(sortItem.Key);
                    }
                    else
                    {
                        sbb.Descending(sortItem.Key);
                    }
                }
                cursor.SetSortOrder(sbb);
            }

            return(cursor.ToList());
        }
Beispiel #22
0
        private void ApplySorting(MongoCursor <BsonDocument> cursor, IEnumerable <SimpleOrderByItem> orderings)
        {
            if (orderings == null || !orderings.Any())
            {
                return;
            }

            var sortBuilder = new SortByBuilder();

            foreach (var ordering in orderings)
            {
                var name = ExpressionFormatter.GetFullName(ordering.Reference);
                if (ordering.Direction == OrderByDirection.Ascending)
                {
                    sortBuilder.Ascending(name);
                }
                else
                {
                    sortBuilder.Descending(name);
                }
            }

            cursor.SetSortOrder(sortBuilder);
        }
        private void ApplySorting(MongoCursor<BsonDocument> cursor, IEnumerable<SimpleOrderByItem> orderings)
        {
            if (orderings == null || !orderings.Any())
                return;

            var sortBuilder = new SortByBuilder();
            foreach (var ordering in orderings)
            {
                var name = ExpressionFormatter.GetFullName(ordering.Reference);
                if (ordering.Direction == OrderByDirection.Ascending)
                    sortBuilder.Ascending(name);
                else
                    sortBuilder.Descending(name);
            }

            cursor.SetSortOrder(sortBuilder);
        }
        public async Task <DataResult <Task <DomainProjectForAdmin> > > GetAsyncSequenceAsync(DataQueryOptions filter)
        {
            var query = new List <IMongoQuery>(filter.Filters.Count);

            // filtering
            List <DataFilterRule> filters = filter.Filters.Where(f => f.Value != null).ToList();

            foreach (DataFilterRule dataFilterRule in filters)
            {
                DataFilterRule f = dataFilterRule;

                if (string.Compare(f.Name, NameOfHelper.PropertyName <DomainProjectForAdmin>(x => x.Name),
                                   StringComparison.OrdinalIgnoreCase) == 0 && f.Type == DataFilterTypes.Equal)
                {
                    // by name
                    query.Add(Query.Text(f.Value.ToString().ToLowerInvariant()));
                }
                else if (string.Compare(f.Name, NameOfHelper.PropertyName <DomainProjectForAdmin>(x => x.ProductType),
                                        StringComparison.OrdinalIgnoreCase) == 0 && f.Type == DataFilterTypes.Equal)
                {
                    // by product type
                    var productId = Int32.Parse(f.Value.ToString());
                    query.Add(Query <ProjectEntity> .EQ(p => p.ProductId, productId));
                }
                else if (string.Compare(f.Name, NameOfHelper.PropertyName <DomainProjectForAdmin>(x => x.UserId),
                                        StringComparison.OrdinalIgnoreCase) == 0 && f.Type == DataFilterTypes.Equal)
                {
                    // by user id
                    query.Add(Query <ProjectEntity> .EQ(p => p.UserId, f.Value.ToString()));
                }
                else if (string.Compare(f.Name, NameOfHelper.PropertyName <DomainProjectForAdmin>(x => x.UserName),
                                        StringComparison.OrdinalIgnoreCase) == 0 && f.Type == DataFilterTypes.Equal)
                {
                    // by user name
                    List <UserEntity> profiles = await _userRepository.FindByNameAsync(f.Value.ToString());

                    if (profiles.Count == 0)
                    {
                        // no users found
                        return(new DataResult <Task <DomainProjectForAdmin> >(new Task <DomainProjectForAdmin>[] { }));
                    }

                    List <string> allIds = profiles.Select(prof => prof.Id).ToList();
                    query.Add(Query <ProjectEntity> .Where(p => allIds.Contains(p.UserId)));
                }
                else if (string.Compare(f.Name, NameOfHelper.PropertyName <DomainProjectForAdmin>(x => x.Created),
                                        StringComparison.OrdinalIgnoreCase) == 0)
                {
                    // by created date
                    var date = (DateTime)f.Value;
                    switch (f.Type)
                    {
                    case DataFilterTypes.Equal:
                        query.Add(Query <ProjectEntity> .EQ(p => p.Created, date));
                        break;

                    case DataFilterTypes.LessThan:
                        query.Add(Query <ProjectEntity> .LT(p => p.Created, date));
                        break;

                    case DataFilterTypes.LessThanOrEqual:
                        query.Add(Query <ProjectEntity> .LTE(p => p.Created, date));
                        break;

                    case DataFilterTypes.GreaterThan:
                        query.Add(Query <ProjectEntity> .GT(p => p.Created, date));
                        break;

                    case DataFilterTypes.GreaterThanOrEqual:
                        query.Add(Query <ProjectEntity> .GTE(p => p.Created, date));
                        break;
                    }
                }
                else
                {
                    throw new NotSupportedException(string.Format("Filter {0} by property {1} is not supported", f.Type, f.Name));
                }
            }

            if (!filters.Any() && !string.IsNullOrEmpty(filter.OrderBy))
            {
                // MongoDb 2.6 HACK!!!
                // adding fake query to hint proper index

                if (string.Compare(filter.OrderBy, NameOfHelper.PropertyName <DomainProjectForAdmin>(x => x.Name),
                                   StringComparison.OrdinalIgnoreCase) == 0)
                {
                    // order by name
                    query.Add(Query <ProjectEntity> .Exists(p => p.Name));
                }
                else if (string.Compare(filter.OrderBy, NameOfHelper.PropertyName <DomainProjectForAdmin>(x => x.Created),
                                        StringComparison.OrdinalIgnoreCase) == 0)
                {
                    // order by created
                    query.Add(Query <ProjectEntity> .Exists(p => p.Created));
                }
                else if (string.Compare(filter.OrderBy, NameOfHelper.PropertyName <DomainProjectForAdmin>(x => x.ProductType),
                                        StringComparison.OrdinalIgnoreCase) == 0)
                {
                    // order by product type
                    query.Add(Query <ProjectEntity> .Exists(p => p.ProductId));
                }
            }

            MongoCursor <ProjectEntity> cursor = _projectRepository.Collection.Find(query.Count > 0 ? Query.And(query) : Query.Null);
            IMongoSortBy sortOrder             = null;

            // sorting
            if (string.Compare(filter.OrderBy, NameOfHelper.PropertyName <DomainProjectForAdmin>(x => x.Name),
                               StringComparison.OrdinalIgnoreCase) == 0)
            {
                // order by name
                sortOrder = filter.OrderByDirection == OrderByDirections.Asc
                    ? SortBy <ProjectEntity> .Ascending(p => p.Name)
                    : SortBy <ProjectEntity> .Descending(p => p.Name);
            }
            else if (string.Compare(filter.OrderBy, NameOfHelper.PropertyName <DomainProjectForAdmin>(x => x.Created),
                                    StringComparison.OrdinalIgnoreCase) == 0)
            {
                // order by created
                sortOrder = filter.OrderByDirection == OrderByDirections.Asc
                    ? SortBy <ProjectEntity> .Ascending(p => p.Created)
                    : SortBy <ProjectEntity> .Descending(p => p.Created);
            }
            else if (string.Compare(filter.OrderBy, NameOfHelper.PropertyName <DomainProjectForAdmin>(x => x.ProductType),
                                    StringComparison.OrdinalIgnoreCase) == 0)
            {
                // order by product type
                sortOrder = filter.OrderByDirection == OrderByDirections.Asc
                    ? SortBy <ProjectEntity> .Ascending(p => p.ProductId)
                    : SortBy <ProjectEntity> .Descending(p => p.ProductId);
            }

            if (sortOrder != null)
            {
                cursor.SetSortOrder(sortOrder);
            }

            // paging

            if (filter.Skip.HasValue)
            {
                cursor.SetSkip(filter.Skip.Value);
            }

            if (filter.Take.HasValue)
            {
                cursor.SetLimit(filter.Take.Value);
            }

            // Count of results
            long?count = null;

            if (filter.Count)
            {
                count = cursor.Count();
            }

            // post-processing

            return(new DataResult <Task <DomainProjectForAdmin> >(cursor.Select(GetProjectDataAsync), count));
        }
        public DataResult <Task <DomainUserForAdmin> > GetAsyncSequence(DataQueryOptions filter)
        {
            var query = new List <IMongoQuery>(filter.Filters.Count);

            // filtering
            List <DataFilterRule> filters = filter.Filters.Where(f => f.Value != null).ToList();

            foreach (DataFilterRule dataFilterRule in filters)
            {
                DataFilterRule f = dataFilterRule;

                if (string.Compare(f.Name, NameOfHelper.PropertyName <DomainUserForAdmin>(x => x.UserName),
                                   StringComparison.OrdinalIgnoreCase) == 0 && f.Type == DataFilterTypes.Equal)
                {
                    // by user name
                    query.Add(Query.Text(f.Value.ToString().ToLowerInvariant()));
                }
                else if (string.Compare(f.Name, NameOfHelper.PropertyName <DomainUserForAdmin>(x => x.Email),
                                        StringComparison.OrdinalIgnoreCase) == 0 && f.Type == DataFilterTypes.Equal)
                {
                    // by email
                    string email      = f.Value.ToString().ToLowerInvariant();
                    var    expression = new BsonRegularExpression(string.Format("^{0}.*", Regex.Escape(email)));
                    query.Add(Query <UserEntity> .Matches(p => p.Email, expression));
                }
                else if (string.Compare(f.Name, NameOfHelper.PropertyName <DomainUserForAdmin>(x => x.ProductType),
                                        StringComparison.OrdinalIgnoreCase) == 0 && f.Type == DataFilterTypes.Equal)
                {
                    // by product type
                    var productId = Int32.Parse(f.Value.ToString());
                    query.Add(Query <UserEntity> .EQ(p => p.ProductId, productId));
                }
                else if (string.Compare(f.Name, NameOfHelper.PropertyName <DomainUserForAdmin>(x => x.Created),
                                        StringComparison.OrdinalIgnoreCase) == 0)
                {
                    // by created date
                    var date = (DateTime)f.Value;
                    switch (f.Type)
                    {
                    case DataFilterTypes.Equal:
                        query.Add(Query <UserEntity> .EQ(p => p.Created, date));
                        break;

                    case DataFilterTypes.LessThan:
                        query.Add(Query <UserEntity> .LT(p => p.Created, date));
                        break;

                    case DataFilterTypes.LessThanOrEqual:
                        query.Add(Query <UserEntity> .LTE(p => p.Created, date));
                        break;

                    case DataFilterTypes.GreaterThan:
                        query.Add(Query <UserEntity> .GT(p => p.Created, date));
                        break;

                    case DataFilterTypes.GreaterThanOrEqual:
                        query.Add(Query <UserEntity> .GTE(p => p.Created, date));
                        break;
                    }
                }
                else
                {
                    throw new NotSupportedException(string.Format("Filter {0} by property {1} is not supported", f.Type, f.Name));
                }
            }

            // Filter only users
            query.Add(Query <UserEntity> .EQ(p => p.Roles, DomainRoles.User));

            MongoCursor <UserEntity> cursor    = _userRepository.Collection.Find(query.Count > 0 ? Query.And(query) : Query.Null);
            IMongoSortBy             sortOrder = null;

            // sorting
            if (string.Compare(filter.OrderBy, NameOfHelper.PropertyName <DomainUserForAdmin>(x => x.UserName),
                               StringComparison.OrdinalIgnoreCase) == 0)
            {
                // order by name
                sortOrder = filter.OrderByDirection == OrderByDirections.Asc
                    ? SortBy <UserEntity> .Ascending(p => p.Name)
                    : SortBy <UserEntity> .Descending(p => p.Name);
            }
            else if (string.Compare(filter.OrderBy, NameOfHelper.PropertyName <DomainUserForAdmin>(x => x.Created),
                                    StringComparison.OrdinalIgnoreCase) == 0)
            {
                // order by created
                sortOrder = filter.OrderByDirection == OrderByDirections.Asc
                    ? SortBy <UserEntity> .Ascending(p => p.Created)
                    : SortBy <UserEntity> .Descending(p => p.Created);
            }
            else if (string.Compare(filter.OrderBy, NameOfHelper.PropertyName <DomainUserForAdmin>(x => x.ProductType),
                                    StringComparison.OrdinalIgnoreCase) == 0)
            {
                // order by product type
                sortOrder = filter.OrderByDirection == OrderByDirections.Asc
                    ? SortBy <UserEntity> .Ascending(p => p.ProductId)
                    : SortBy <UserEntity> .Descending(p => p.ProductId);
            }

            if (sortOrder != null)
            {
                cursor.SetSortOrder(sortOrder);
            }

            // paging

            if (filter.Skip.HasValue)
            {
                cursor.SetSkip(filter.Skip.Value);
            }

            if (filter.Take.HasValue)
            {
                cursor.SetLimit(filter.Take.Value);
            }

            // Count of results
            long?count = null;

            if (filter.Count)
            {
                count = cursor.Count();
            }

            // post-processing

            return(new DataResult <Task <DomainUserForAdmin> >(cursor.Select(GetUserDataAsync), count));
        }
Beispiel #26
0
        public GetToDosDataResponse FindToDos(object request)
        {
            GetToDosDataResponse response    = new GetToDosDataResponse();
            List <ToDoData>      todoList    = null;
            GetToDosDataRequest  dataRequest = (GetToDosDataRequest)request;

            try
            {
                using (SchedulingMongoContext ctx = new SchedulingMongoContext(_dbName))
                {
                    List <IMongoQuery> queries = new List <IMongoQuery>();
                    queries.Add(Query.EQ(METoDo.DeleteFlagProperty, false));
                    if (!string.IsNullOrEmpty(dataRequest.AssignedToId))
                    {
                        ObjectId ato;
                        if (ObjectId.TryParse(dataRequest.AssignedToId, out ato))
                        {
                            queries.Add(Query.EQ(METoDo.AssignedToProperty, ato));
                        }
                        else
                        {
                            // Fix for bug  - ENG-1068, UI sends AssignedToId = -1 to query on all unassigned ToDos.
                            if (string.Compare(dataRequest.AssignedToId, "-1", true) == 0)
                            {
                                //queries.Add(Query.Or(Query.EQ(METoDo.AssignedToProperty, BsonNull.Value), Query.EQ(METoDo.AssignedToProperty, BsonString.Empty)));
                                queries.Add(Query.In(METoDo.AssignedToProperty, new BsonArray {
                                    BsonNull.Value, BsonString.Empty
                                }));
                            }
                        }
                    }
                    if (!string.IsNullOrEmpty(dataRequest.NotAssignedToId))
                    {
                        ObjectId nto;
                        if (ObjectId.TryParse(dataRequest.NotAssignedToId, out nto))
                        {
                            queries.Add(Query.NotIn(METoDo.AssignedToProperty, new BsonArray {
                                nto, BsonNull.Value, BsonString.Empty
                            }));
                        }
                    }
                    if (!string.IsNullOrEmpty(dataRequest.CreatedById))
                    {
                        queries.Add(Query.EQ(METoDo.RecordCreatedByProperty, ObjectId.Parse(dataRequest.CreatedById)));
                    }
                    if (!string.IsNullOrEmpty(dataRequest.PatientId))
                    {
                        queries.Add(Query.EQ(METoDo.PatientIdProperty, ObjectId.Parse(dataRequest.PatientId)));
                    }
                    if (dataRequest.StatusIds != null && dataRequest.StatusIds.Count > 0)
                    {
                        queries.Add(Query.In(METoDo.StatusProperty, new BsonArray(dataRequest.StatusIds)));
                    }
                    if (dataRequest.PriorityIds != null && dataRequest.PriorityIds.Count > 0)
                    {
                        queries.Add(Query.In(METoDo.PriorityProperty, new BsonArray(dataRequest.PriorityIds))); //integer values (not object ids)
                    }
                    if (dataRequest.CategoryIds != null && dataRequest.CategoryIds.Count > 0)
                    {
                        List <BsonValue> categories = new List <BsonValue>();
                        foreach (string categoryId in dataRequest.CategoryIds)
                        {
                            if (categoryId.Length > 0)
                            {
                                categories.Add(BsonValue.Create(ObjectId.Parse(categoryId)));
                            }
                            else
                            {
                                categories.Add(BsonNull.Value); //empty string => include null categories ( not set )
                            }
                        }
                        queries.Add(Query.In(METoDo.CatgegoryProperty, categories));
                    }
                    if (dataRequest.FromDate != null)
                    {
                        queries.Add(Query.GTE(METoDo.ClosedDateProperty, dataRequest.FromDate));
                    }

                    IMongoQuery          mQuery  = Query.And(queries);
                    MongoCursor <METoDo> cToDos  = ctx.ToDos.Collection.Find(mQuery);
                    List <METoDo>        meToDos = null;
                    SortByBuilder        sortBy  = MongoSortingUtils.GetSortByBuilder(dataRequest.Sort, typeof(METoDo));
                    cToDos = cToDos.SetSortOrder(sortBy);
                    cToDos = (MongoCursor <METoDo>)MongoSortingUtils.ApplySkipTake(cToDos, dataRequest);
                    response.TotalCount = cToDos.Count();
                    meToDos             = cToDos.ToList(); //query now

                    if (meToDos != null && meToDos.Count > 0)
                    {
                        todoList = new List <ToDoData>();
                        foreach (METoDo t in meToDos)
                        {
                            todoList.Add(new ToDoData
                            {
                                AssignedToId     = t.AssignedToId == null ? string.Empty : t.AssignedToId.ToString(),
                                CategoryId       = t.Category == null ? string.Empty : t.Category.ToString(),
                                ClosedDate       = t.ClosedDate,
                                CreatedById      = t.RecordCreatedBy.ToString(),
                                CreatedOn        = t.RecordCreatedOn,
                                Description      = t.Description,
                                DueDate          = t.DueDate,
                                StartTime        = t.StartTime,
                                Duration         = t.Duration,
                                Id               = t.Id.ToString(),
                                PatientId        = t.PatientId == null ? string.Empty : t.PatientId.ToString(),
                                PriorityId       = (int)t.Priority,
                                ProgramIds       = Helper.ConvertToStringList(t.ProgramIds),
                                StatusId         = (int)t.Status,
                                Title            = t.Title,
                                UpdatedOn        = t.LastUpdatedOn,
                                DeleteFlag       = t.DeleteFlag,
                                ExternalRecordId = t.ExternalRecordId,
                                SourceId         = t.SourceId.ToString()
                            });
                        }
                    }
                }
                response.ToDos = todoList;
                return(response);
            }
            catch (Exception ex)
            {
                throw new Exception("DD:MongoToDoRepository:FindToDos()::" + ex.Message, ex.InnerException);
            }
        }
    public List <BsonDocument> ExecuteQueryBsonDoc(string table,                 // 表名
                                                   IMongoQuery query,            // 查询条件,外部要自拼接
                                                   string[] fields  = null,
                                                   string sort      = "",
                                                   bool asc         = true,
                                                   int skip         = 0,
                                                   int limt         = 0,
                                                   string[] indexes = null)
    {
        // 表不存在,直接返回
        if (!TableExists(table))
        {
            return(null);
        }

        List <BsonDocument> retlist = new List <BsonDocument>();

        try
        {
            var cb = check_table(table);
            MongoCursor <BsonDocument> ret = null;
            if (query == null)
            {
                ret = cb.FindAll();
            }
            else
            {
                ret = cb.Find(query);
            }

            if (fields != null)
            {
                ret = ret.SetFields(fields);
            }

            if (sort != string.Empty)
            {
                if (asc)
                {
                    ret = ret.SetSortOrder(SortBy.Ascending(sort));
                }
                else
                {
                    ret = ret.SetSortOrder(SortBy.Descending(sort));
                }
            }

            if (skip > 0)
            {
                ret = ret.SetSkip(skip);
            }
            if (limt > 0)
            {
                ret = ret.SetLimit(limt);
            }

            var it = ret.GetEnumerator();

            while (it.MoveNext())
            {
                retlist.Add(it.Current);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            retlist.Clear();
        }
        return(retlist);
    }
Beispiel #28
0
        internal void Set(MongoCursor cursor)
        {
            if (cursor == null)
                return;

            if (Skip != -1)
            {
                cursor.Skip = Skip;
            }
            if (Limit != -1)
            {
                cursor.Limit = Limit;
            }
            if (Fields != null)
            {
                cursor.Fields = Fields;
            }
            if (SortBy != null)
            {
                cursor.SetSortOrder(SortBy);
            }
        }
Beispiel #29
0
        public PagedResult <Organization> List(string criteria = null, bool?isPaidPlan = null, bool?isSuspended = null, OrganizationSortBy sortBy = OrganizationSortBy.Newest, int page = 1, int pageSize = 10)
        {
            int skip = (page - 1) * pageSize;

            if (skip < 0)
            {
                skip = 0;
            }

            if (pageSize < 1)
            {
                pageSize = 10;
            }

            var queries = new List <IMongoQuery>();

            if (!String.IsNullOrWhiteSpace(criteria))
            {
                queries.Add(Query.Matches(OrganizationRepository.FieldNames.Name, new BsonRegularExpression(String.Format("/{0}/i", criteria))));
            }

            if (isPaidPlan.HasValue)
            {
                if (isPaidPlan.Value)
                {
                    queries.Add(Query.NE(OrganizationRepository.FieldNames.PlanId, new BsonString(BillingManager.FreePlan.Id)));
                }
                else
                {
                    queries.Add(Query.EQ(OrganizationRepository.FieldNames.PlanId, new BsonString(BillingManager.FreePlan.Id)));
                }
            }

            if (isSuspended.HasValue)
            {
                if (isSuspended.Value)
                {
                    queries.Add(
                        Query.Or(
                            Query.And(
                                Query.NE(OrganizationRepository.FieldNames.BillingStatus, new BsonInt32((int)BillingStatus.Active)),
                                Query.NE(OrganizationRepository.FieldNames.BillingStatus, new BsonInt32((int)BillingStatus.Trialing)),
                                Query.NE(OrganizationRepository.FieldNames.BillingStatus, new BsonInt32((int)BillingStatus.Canceled))),
                            Query.EQ(OrganizationRepository.FieldNames.IsSuspended, new BsonBoolean(true))));
                }
                else
                {
                    queries.Add(Query.And(
                                    Query.Or(
                                        Query.EQ(OrganizationRepository.FieldNames.BillingStatus, new BsonInt32((int)BillingStatus.Active)),
                                        Query.EQ(OrganizationRepository.FieldNames.BillingStatus, new BsonInt32((int)BillingStatus.Trialing)),
                                        Query.EQ(OrganizationRepository.FieldNames.BillingStatus, new BsonInt32((int)BillingStatus.Canceled))),
                                    Query.EQ(OrganizationRepository.FieldNames.IsSuspended, new BsonBoolean(false))));
                }
            }

            SortByBuilder sort;

            if (sortBy == OrganizationSortBy.Newest)
            {
                sort = SortBy.Descending(OrganizationRepository.FieldNames.Id);
            }
            else if (sortBy == OrganizationSortBy.Subscribed)
            {
                sort = SortBy.Descending(OrganizationRepository.FieldNames.SubscribeDate);
            }
            else if (sortBy == OrganizationSortBy.MostActive)
            {
                sort = SortBy.Descending(OrganizationRepository.FieldNames.TotalErrorCount);
            }
            else
            {
                sort = SortBy.Ascending(OrganizationRepository.FieldNames.Name);
            }

            MongoCursor <Organization> query   = queries.Count > 0 ? ((OrganizationRepository)_repository).Collection.Find(Query.And(queries)) : ((OrganizationRepository)_repository).Collection.FindAll();
            List <Organization>        results = query.SetSortOrder(sort).SetSkip(skip).SetLimit(pageSize).ToList();

            return(new PagedResult <Organization>(results)
            {
                Page = page,
                PageSize = pageSize,
                TotalCount = query.Count()
            });
        }
 public IMongoCursor SetSortOrder(IMongoSortBy sortBy)
 {
     return(new MongoCursorProxy(_mongoMongoCursor.SetSortOrder(sortBy)));
 }
        public async Task <DataResult <Watch> > GetSequenceAsync(DataQueryOptions filter, string userId)
        {
            var query = new List <IMongoQuery>(filter.Filters.Count);

            // Filtering
            List <DataFilterRule> filters = filter.Filters.Where(f => f.Value != null).ToList();
            string requestedUserId        = null;
            var    searchList             = new List <string>();

            foreach (DataFilterRule dataFilterRule in filters)
            {
                DataFilterRule f = dataFilterRule;

                if (string.Compare(f.Name, NameOfHelper.PropertyName <Watch>(x => x.Name),
                                   StringComparison.OrdinalIgnoreCase) == 0 && f.Type == DataFilterTypes.Equal)
                {
                    // by name
                    searchList.Add(f.Value.ToString().ToLowerInvariant());
                }
                else if (string.Compare(f.Name, NameOfHelper.PropertyName <Watch>(x => x.UserId),
                                        StringComparison.OrdinalIgnoreCase) == 0 && f.Type == DataFilterTypes.Equal)
                {
                    // by user id
                    requestedUserId = f.Value.ToString();
                    query.Add(Query <ProjectEntity> .EQ(p => p.UserId, requestedUserId));
                }
                else if (string.Compare(f.Name, NameOfHelper.PropertyName <Watch>(x => x.Generator),
                                        StringComparison.OrdinalIgnoreCase) == 0 && f.Type == DataFilterTypes.Equal)
                {
                    // by product id
                    int productId = Int32.Parse(f.Value.ToString());
                    query.Add(Query <ProjectEntity> .EQ(p => p.ProductId, productId));
                }
                else if (string.Compare(f.Name, NameOfHelper.PropertyName <Watch>(x => x.ProjectType),
                                        StringComparison.OrdinalIgnoreCase) == 0 && f.Type == DataFilterTypes.Equal)
                {
                    // by project type
                    object projectType = Enum.Parse(typeof(ProjectType), f.Value.ToString());
                    query.Add(Query <ProjectEntity> .EQ(p => p.ProjectType, (int)projectType));
                }
                else if (string.Compare(f.Name, NameOfHelper.PropertyName <Watch>(x => x.ProjectSubtype),
                                        StringComparison.OrdinalIgnoreCase) == 0 && f.Type == DataFilterTypes.Equal)
                {
                    // by project subtype
                    object projectSubtype = Enum.Parse(typeof(ProjectSubtype), f.Value.ToString());
                    query.Add(Query <ProjectEntity> .EQ(p => p.ProjectSubtype, (int)projectSubtype));
                }
                else if (string.Compare(f.Name, NameOfHelper.PropertyName <Watch>(x => x.External.VideoUri),
                                        StringComparison.OrdinalIgnoreCase) == 0 && f.Type == DataFilterTypes.Equal)
                {
                    // by external video uri
                    query.Add(Query <ProjectEntity> .EQ(p => p.VideoSource, f.Value));
                }
                else if (string.Compare(f.Name, NameOfHelper.PropertyName <Watch>(x => x.Created),
                                        StringComparison.OrdinalIgnoreCase) == 0)
                {
                    // by created date
                    var date = (DateTime)f.Value;
                    switch (f.Type)
                    {
                    case DataFilterTypes.Equal:
                        query.Add(Query <ProjectEntity> .EQ(p => p.Created, date));
                        break;

                    case DataFilterTypes.LessThan:
                        query.Add(Query <ProjectEntity> .LT(p => p.Created, date));
                        break;

                    case DataFilterTypes.LessThanOrEqual:
                        query.Add(Query <ProjectEntity> .LTE(p => p.Created, date));
                        break;

                    case DataFilterTypes.GreaterThan:
                        query.Add(Query <ProjectEntity> .GT(p => p.Created, date));
                        break;

                    case DataFilterTypes.GreaterThanOrEqual:
                        query.Add(Query <ProjectEntity> .GTE(p => p.Created, date));
                        break;
                    }
                }
                else if (string.Compare(f.Name, NameOfHelper.PropertyName <Watch>(x => x.HitsCount),
                                        StringComparison.OrdinalIgnoreCase) == 0)
                {
                    // by hits count
                    int threshold = Int32.Parse(f.Value.ToString());

                    if (f.Type == DataFilterTypes.GreaterThan)
                    {
                        query.Add(Query <ProjectEntity> .GT(p => p.HitsCount, threshold));
                    }
                    else if (f.Type == DataFilterTypes.GreaterThanOrEqual)
                    {
                        query.Add(Query <ProjectEntity> .GTE(p => p.HitsCount, threshold));
                    }
                    else
                    {
                        query.Add(Query <ProjectEntity> .EQ(p => p.HitsCount, threshold));
                    }
                }
                else if (string.Compare(f.Name, NameOfHelper.PropertyName <Watch>(x => x.State),
                                        StringComparison.OrdinalIgnoreCase) == 0 && f.Type == DataFilterTypes.Equal)
                {
                    // by video state
                    var videoState = (WatchState)Enum.Parse(typeof(WatchState), f.Value.ToString());
                    if (videoState == WatchState.Uploading)
                    {
                        var avsx = Query <ProjectEntity> .EQ(p => p.AvsxFileId, null);

                        var originalFileId = Query <ProjectEntity> .EQ(p => p.OriginalVideoFileId, null);

                        var externalSource = Query <ProjectEntity> .EQ(p => p.VideoSource, null);

                        query.Add(Query.Or(avsx, Query.And(originalFileId, externalSource)));
                    }
                    else if (videoState == WatchState.Encoding)
                    {
                        var avsx = Query <ProjectEntity> .NE(p => p.AvsxFileId, null);

                        var originalFileId = Query <ProjectEntity> .NE(p => p.OriginalVideoFileId, null);

                        var encodedVideosName = NameOfHelper.PropertyName <ProjectEntity>(x => x.EncodedVideos);
                        var encodedVideos     = Query.NotExists(string.Format("{0}.0", encodedVideosName));

                        query.Add(Query.And(avsx, originalFileId, encodedVideos));
                    }
                    else if (videoState == WatchState.Ready)
                    {
                        var avsx = Query <ProjectEntity> .NE(p => p.AvsxFileId, null);

                        var externalSource = Query <ProjectEntity> .NE(p => p.VideoSource, null);

                        var originalFileId = Query <ProjectEntity> .NE(p => p.OriginalVideoFileId, null);

                        var encodedVideosName = NameOfHelper.PropertyName <ProjectEntity>(x => x.EncodedVideos);
                        var encodedVideos     = Query.Exists(string.Format("{0}.0", encodedVideosName));

                        query.Add(Query.And(avsx, Query.Or(externalSource, Query.And(originalFileId, encodedVideos))));
                    }
                }
                else
                {
                    throw new NotSupportedException(string.Format("Filter {0} by property {1} is not supported", f.Type, f.Name));
                }
            }

            string searchText = String.Join(" ", searchList);

            if (!String.IsNullOrEmpty(searchText))
            {
                query.Add(Query.Text(searchText));
            }

            // we should see only public videos for other users
            if (requestedUserId != userId)
            {
                query.Add(Query <ProjectEntity> .EQ(p => p.Access, (int)ProjectAccess.Public));
            }

            MongoCursor <ProjectEntity> cursor = _projectRepository.Collection.Find(query.Count > 0 ? Query.And(query) : Query.Null);

            // Sorting
            IMongoSortBy sortOrder = null;

            if (string.Compare(filter.OrderBy, NameOfHelper.PropertyName <Watch>(x => x.Name),
                               StringComparison.OrdinalIgnoreCase) == 0)
            {
                // order by name
                sortOrder = filter.OrderByDirection == OrderByDirections.Asc
                    ? SortBy <ProjectEntity> .Ascending(p => p.Name)
                    : SortBy <ProjectEntity> .Descending(p => p.Name);
            }
            else if (string.Compare(filter.OrderBy, NameOfHelper.PropertyName <Watch>(x => x.Created),
                                    StringComparison.OrdinalIgnoreCase) == 0)
            {
                // order by created
                sortOrder = filter.OrderByDirection == OrderByDirections.Asc
                    ? SortBy <ProjectEntity> .Ascending(p => p.Created)
                    : SortBy <ProjectEntity> .Descending(p => p.Created);
            }
            else if (string.Compare(filter.OrderBy, NameOfHelper.PropertyName <Watch>(x => x.HitsCount),
                                    StringComparison.OrdinalIgnoreCase) == 0)
            {
                // order by hits count
                sortOrder = filter.OrderByDirection == OrderByDirections.Asc
                    ? SortBy <ProjectEntity> .Ascending(p => p.HitsCount)
                    : SortBy <ProjectEntity> .Descending(p => p.HitsCount);
            }

            if (sortOrder != null)
            {
                cursor.SetSortOrder(sortOrder);
            }

            // Paging
            if (filter.Skip.HasValue)
            {
                cursor.SetSkip(filter.Skip.Value);
            }
            if (filter.Take.HasValue)
            {
                cursor.SetLimit(filter.Take.Value);
            }

            // Count of results
            long?count = null;

            if (filter.Count)
            {
                count = cursor.Count();
            }

            List <ProjectEntity> projects = cursor.ToList();

            // Get comments and total comment counts
            string[] projectIds = projects.Select(p => p.Id).ToArray();
            Dictionary <string, int> commentsCounts = (await _commentRepository.GetCommentsCountByProjectsAsync(projectIds)).ToDictionary(c => c.ProjectId, c => c.CommentsCount);
            Dictionary <string, List <CommentEntity> > recentComments = await _commentRepository.GetRecentCommentsByProjectsAsync(projectIds, RecentCommentsLimit);

            // Get project user ids united with comment user ids to load entities in batch
            string[] userIds = GetUserIds(projects, recentComments);
            Dictionary <string, UserEntity> users = (await _userRepository.GetUsersByIdsAsync(userIds)).ToDictionary(u => u.Id);

            // Post-processing
            return(new DataResult <Watch>(projects.Select(p => AggregateProject(p, userId, users, commentsCounts, recentComments)), count));
        }