Ejemplo n.º 1
0
        public static FilterDefinition <TDocument> NotDeactivated <TDocument, TItem>(FilterDefinitionBuilder <TDocument> builder, Expression <Func <TDocument, IEnumerable <TItem> > > acessor, DateTime?dateTime = null) where TItem : IActivationAware
        {
            var twoBuilder = new FilterDefinitionBuilder <TItem>();

            if (!dateTime.HasValue)
            {
                dateTime = DateTime.UtcNow;
            }
            return(builder.Or
                   (
                       builder.Not
                       (
                           builder.ElemMatch
                           (
                               acessor,
                               twoBuilder.Exists
                               (
                                   t => t.DeactivationDate
                               )
                           )
                       ),
                       builder.ElemMatch
                       (
                           acessor,
                           twoBuilder.Gt
                           (
                               t => t.DeactivationDate,
                               dateTime.Value
                           )
                       )
                   ));
        }
Ejemplo n.º 2
0
        public override FilterDefinition <T> VisitIntOp([NotNull] FilterParser.IntOpContext context)
        {
            string id      = context.ID().GetText();
            string integer = context.INT().GetText();

            var op = context.op.Type;

            switch (op)
            {
            case FilterParser.EQ:
                return(_builder.Eq(id, integer));

            case FilterParser.NE:
                return(_builder.Ne(id, integer));

            case FilterParser.GT:
                return(_builder.Gt(id, integer));

            case FilterParser.GE:
                return(_builder.Gte(id, integer));

            case FilterParser.LT:
                return(_builder.Lt(id, integer));

            case FilterParser.LE:
                return(_builder.Lte(id, integer));

            default:
                throw new InvalidOperationException($"Invalid StringOp {context.GetText()}");
            }
        }
        //提交
        private void CommitTransfer(TransactionDocument txn, TimeSpan maxTxnTime)
        {
            DateTime now    = DateTime.Now.ToUniversalTime();
            DateTime cutOff = now - maxTxnTime;

            //更新事务文档
            FilterDefinitionBuilder <TransactionDocument> filterBuilder = Builders <TransactionDocument> .Filter;
            FilterDefinition <TransactionDocument>        filter1       = filterBuilder.Eq(m => m._id, txn._id);
            FilterDefinition <TransactionDocument>        filter2       = filterBuilder.Gt(m => m.Ts, cutOff);
            FilterDefinition <TransactionDocument>        filter        = filterBuilder.And(new FilterDefinition <TransactionDocument>[] { filter1, filter2 });

            var update = Builders <TransactionDocument> .Update.Set(m => m.State, "commit");

            UpdateResult updateResult = mongoDBService.DocumentUpdate(TransactionCollectionName, filter, update);
            bool         isSuccess    = updateResult.ModifiedCount > 0 && updateResult.ModifiedCount == updateResult.MatchedCount ?
                                        true : false;

            if (!isSuccess)
            {
                throw new Exception("修改事务文档失败");
            }
            else
            {
                RetireTransaction(txn);
            }
        }
Ejemplo n.º 4
0
        public async Task <IAsyncCursor <BsonDocument> > GetCursor(ResumeToken resumeToken,
                                                                   IEnumerable <string> collections,
                                                                   CancellationToken cancellationToken)
        {
            BsonValue ts;

            if (resumeToken.Token != null)
            {
                ts = resumeToken.Token["ts"];
            }
            else
            {
                var operation = await operations
                                .Find(new BsonDocument())
                                .Sort(Builders <BsonDocument> .Sort.Descending("$natural"))
                                .FirstAsync(cancellationToken);

                ts = operation["ts"];
            }

            var filter = builder.And(
                builder.In("op", new[] { "i", "u", "d" }),
                builder.Gt("ts", ts),
                builder.In("ns", collections.Select(collectionName => $"{databaseName}.{collectionName}")),
                builder.Exists("fromMigrate", false)
                );

            var options = new FindOptions <BsonDocument>
            {
                CursorType = CursorType.TailableAwait, NoCursorTimeout = true, OplogReplay = true
            };

            return(await operations.FindAsync(filter, options, cancellationToken));
        }
Ejemplo n.º 5
0
 public async Task WhenGet_Grade_Score_Greater_Than_Returns_RestaurantList()
 {
     var collection = _database.GetCollection<BsonDocument>("restaurants");
     var builder = new FilterDefinitionBuilder<BsonDocument>();
     var filter = builder.Gt("grades.score", 20);
     var result = await collection.Find(filter).ToListAsync();
     Assert.AreEqual(6332, result.Count());
 }
Ejemplo n.º 6
0
        public AggregateResponce <Book> GetBooksInStock(BooksInStockQueryParams queryParams)
        {
            if (queryParams == null)
            {
                throw new ArgumentNullException(nameof(queryParams));
            }

            var response = new AggregateResponce <Book>();

            var filter = _filter.Gt(BooksTableFieldNames.Count, 1);

            var filteredResult = _context.Books.Find(filter).Limit(queryParams.GetLimitedItemsNumber);

            if (queryParams.ShowOnlyTitle)
            {
                filteredResult = filteredResult.Project(Builders <BsonDocument> .Projection.Include(BooksTableFieldNames.Name));
            }

            if (queryParams.SortByTitle)
            {
                var sortFilter = new BsonDocument().Add(BooksTableFieldNames.Name, 1);

                filteredResult = filteredResult.Sort(sortFilter);
            }

            if (!queryParams.GetOnlyCount)
            {
                if (queryParams.ShowOnlyTitle)
                {
                    response.Titles = filteredResult.ToEnumerable()
                                      .Select(doc => doc[BooksTableFieldNames.Name].AsString)
                                      .ToList();
                }
                else
                {
                    response.Items = filteredResult.ToEnumerable()
                                     .Select(BookConverter.ConvertDocumentToBook)
                                     .ToList();
                }
            }

            response.AgregateValue = filteredResult.ToEnumerable().Count();

            return(response);
        }
Ejemplo n.º 7
0
        public List <Message> FindMessageByLastDate(ChatRoom chatRoom, long longLastDate)
        {
            var builder    = new FilterDefinitionBuilder <Message>();
            var filterChat = builder.Eq("ChatRoom", chatRoom.ToRef());
            var filterDate = builder.Gt("Date", longLastDate);
            var messages   = messageDao.Find.WhenMatch(filterChat & filterDate, new PageDefinition("Date", false));

            return(new List <Message>(messages));
        }
Ejemplo n.º 8
0
        /* 输入:起止时间
         * 输出:时间段内数据总数
         *
         */
        public int GetDeviceAlarmInfoNumberByTime(DateTime startTime, DateTime endTime)
        {
            FilterDefinitionBuilder <AlarmInfoModel> builderFilter = Builders <AlarmInfoModel> .Filter;
            FilterDefinition <AlarmInfoModel>        filter        = builderFilter.And(
                builderFilter.Gt("Timestamp", startTime),
                builderFilter.Lt("Timestamp", endTime));

            return((int)_alarmInfo.Find(filter).CountDocuments());
        }
Ejemplo n.º 9
0
        public override FilterDefinition <T> Visit(CompareFilter <ClrValue> nodeIn, None args)
        {
            var propertyName = nodeIn.Path.ToString();

            var value = nodeIn.Value.Value;

            switch (nodeIn.Operator)
            {
            case CompareOperator.Empty:
                return(Filter.Or(
                           Filter.Exists(propertyName, false),
                           Filter.Eq <object?>(propertyName, null),
                           Filter.Eq <object?>(propertyName, string.Empty),
                           Filter.Size(propertyName, 0)));

            case CompareOperator.Exists:
                return(Filter.And(
                           Filter.Exists(propertyName, true),
                           Filter.Ne <object?>(propertyName, null)));

            case CompareOperator.Matchs:
                return(Filter.Regex(propertyName, BuildMatchRegex(nodeIn)));

            case CompareOperator.StartsWith:
                return(Filter.Regex(propertyName, BuildRegex(nodeIn, s => "^" + s)));

            case CompareOperator.Contains:
                return(Filter.Regex(propertyName, BuildRegex(nodeIn, s => s)));

            case CompareOperator.EndsWith:
                return(Filter.Regex(propertyName, BuildRegex(nodeIn, s => s + "$")));

            case CompareOperator.Equals:
                return(Filter.Eq(propertyName, value));

            case CompareOperator.GreaterThan:
                return(Filter.Gt(propertyName, value));

            case CompareOperator.GreaterThanOrEqual:
                return(Filter.Gte(propertyName, value));

            case CompareOperator.LessThan:
                return(Filter.Lt(propertyName, value));

            case CompareOperator.LessThanOrEqual:
                return(Filter.Lte(propertyName, value));

            case CompareOperator.NotEquals:
                return(Filter.Ne(propertyName, value));

            case CompareOperator.In:
                return(Filter.In(propertyName, ((IList)value !).OfType <object>()));
            }

            throw new NotSupportedException();
        }
Ejemplo n.º 10
0
        public FilterDefinition <IUser> ConcatenateFilter(List <SearchFilter> filters, FilterDefinitionBuilder <IUser> builder, FilterDefinition <IUser> filter, int i)
        {
            if (filters[i] is SearchFilter)
            {
                switch (filters[i].FieldName)
                {
                case "_id":
                    filter = filter & builder.Ne("_id", ((ValueSearchFilter <string>)filters[i]).Value);
                    break;

                case "UserType":
                    filter = filter & builder.Eq(filters[i].FieldName, ((ValueSearchFilter <string>)filters[i]).Value);
                    break;

                case "Gender":
                    if (((ValueSearchFilter <int>)filters[i]).Value != 2)
                    {
                        filter = filter & builder.Eq(filters[i].FieldName, ((ValueSearchFilter <int>)filters[i]).Value);
                    }
                    break;

                case "Location":
                    break;

                case "Expertise":
                    //ExpertiseEntityService expertiseService = new ExpertiseEntityService();
                    //IExpertise expertiseVal = await expertiseService.GetExpertiseById(((ValueSearchFilter<string>)filters[i]).Value);
                    //expertiseVal.ExpertiseName
                    filter = filter & builder.Eq(filters[i].FieldName, ((ValueSearchFilter <string>)filters[i]).Value);
                    break;

                case "Reputation":
                    filter = filter & builder.Eq(filters[i].FieldName, ((ValueSearchFilter <int>)filters[i]).Value);
                    break;

                case "Showers":
                    filter = filter & builder.Eq(filters[i].FieldName, ((ValueSearchFilter <bool>)filters[i]).Value);
                    break;

                case "ParkingLot":
                    filter = filter & builder.Eq(filters[i].FieldName, ((ValueSearchFilter <bool>)filters[i]).Value);
                    break;
                }
            }
            else
            {
                filter = filter & builder.Lte(filters[i].FieldName, ((RangeSearchFilter)filters[i]).ToValue) &
                         builder.Gt(filters[i].FieldName, ((RangeSearchFilter)filters[i]).FromValue);
            }

            return(filter);
        }
Ejemplo n.º 11
0
 public static FilterDefinition <TDocument> NotDeactivated <TDocument>(FilterDefinitionBuilder <TDocument> builder, DateTime?dateTime = null) where TDocument : IActivationAware
 {
     if (!dateTime.HasValue)
     {
         dateTime = DateTime.UtcNow;
     }
     return(builder.Or(
                builder.Not(
                    builder.Exists(doc => doc.DeactivationDate)
                    ),
                builder.Gt(doc => doc.DeactivationDate, dateTime.Value)
                ));
 }
Ejemplo n.º 12
0
        public void AggregateAllFourOrMoreStarsRestaurants()
        {
            filterBuilder = Builders <Restaurant> .Filter;
            var starFilter     = filterBuilder.Gt("Stars", 3);
            var projectBuilder = Builders <Restaurant> .Projection;
            var projection     = projectBuilder.Include("Name").Include("Stars").Exclude("_id");
            var restaurants    = collection.Aggregate().Match(starFilter).Project(projection).ToList();

            foreach (var restaurant in restaurants)
            {
                Console.WriteLine(restaurant);
            }
        }
Ejemplo n.º 13
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));
        }
Ejemplo n.º 14
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);
            }
        }
Ejemplo n.º 15
0
 public static FilterDefinition <TDocument> NotDeactivated <TDocument, TItem>(FilterDefinitionBuilder <TDocument> builder, Expression <Func <TDocument, TItem> > acessor, DateTime?dateTime = null) where TItem : IActivationAware
 {
     if (!dateTime.HasValue)
     {
         dateTime = DateTime.UtcNow;
     }
     return(builder.Or
            (
                builder.Not
                (
                    builder.Exists
                    (
                        Expression.Lambda <Func <TDocument, object> >
                        (
                            Expression.Convert
                            (
                                Expression.Property
                                (
                                    acessor.Body,
                                    nameof(IActivationAware.DeactivationDate)
                                ),
                                typeof(object)
                            ),
                            acessor.Parameters
                        )
                    )
                ),
                builder.Gt
                (
                    Expression.Lambda <Func <TDocument, DateTime> >
                    (
                        Expression.Convert
                        (
                            Expression.Property
                            (
                                acessor.Body,
                                nameof(IActivationAware.DeactivationDate)
                            ),
                            typeof(DateTime)
                        ),
                        acessor.Parameters
                    ),
                    dateTime.Value
                )
            ));
 }
Ejemplo n.º 16
0
        public async Task FindUsingFilterDefinitionBuilder1Async(IMongoCollection <ClubMember> collection)
        {
            Console.WriteLine("Starting FindUsingFilterDefinitionBuilder1Async");
            DateTime cutOffDate = DateTime.Now.AddYears(-5);
            FilterDefinitionBuilder <ClubMember> builder = Builders <ClubMember> .Filter;
            //A greater than filter. Selects where the MembershipDate is greater than the cutOffDate
            FilterDefinition <ClubMember> filterDefinition = builder.Gt("MembershipDate", cutOffDate.ToUniversalTime());
            //DateTime is stored in BsonElement as a UTC value so need to convert
            List <ClubMember> membersList =
                await collection.Find(filterDefinition).SortBy(c => c.Lastname).ThenBy(c => c.Forename).ToListAsync();

            Console.WriteLine("Finished FindUsingFilterDefinitionBuilder1Async");
            Console.WriteLine("\r\nMembers who have joined in the last 5 years ...");
            foreach (ClubMember clubMember in membersList)
            {
                ConsoleHelper.PrintClubMemberToConsole(clubMember);
            }
        }
        protected override async Task Execute(CancellationToken cancellationToken)
        {
            var checkpoint = await checkpoints.Find(c => c.Name == name).FirstOrDefaultAsync(cancellationToken);

            if (checkpoint is null)
            {
                var @event = await events
                             .Find(Builders <EventEnvelope> .Filter.In("event._t", handlers.Keys))
                             .Sort(Builders <EventEnvelope> .Sort.Descending(envelope => envelope.Timestamp))
                             .FirstOrDefaultAsync(cancellationToken);

                checkpoint = new Checkpoint {
                    Name = name, Position = @event?.Timestamp ?? new BsonTimestamp(0, 0)
                };
                await checkpoints.InsertOneAsync(checkpoint, cancellationToken : cancellationToken);
            }

            while (!cancellationToken.IsCancellationRequested)
            {
                await events
                .Find(filter.And(
                          filter.In("event._t", handlers.Keys),
                          filter.Gt(envelope => envelope.Timestamp, checkpoint.Position)))
                .Sort(Builders <EventEnvelope> .Sort.Ascending(envelope => envelope.Timestamp))
                .ForEachAsync(async envelope =>
                {
                    if (handlers.TryGetValue(envelope.Event.GetType().Name, out var handler))
                    {
                        if (!string.IsNullOrEmpty(envelope.CorrelationId))
                        {
                            TraceContext.Set(envelope.CorrelationId, envelope.EventId);
                        }

                        await handler.Invoke(envelope.Event);
                    }

                    await SaveCheckpoint(checkpoint, envelope.Timestamp);
                }, cancellationToken);

                await Task.Delay(TimeSpan.FromMilliseconds(100), cancellationToken);
            }
        }
Ejemplo n.º 18
0
        public override FilterDefinition <T> Visit(FilterComparison nodeIn)
        {
            var propertyName = string.Join(".", nodeIn.Lhs);

            switch (nodeIn.Operator)
            {
            case FilterOperator.Empty:
                return(Filter.Or(Filter.Exists(propertyName, false), Filter.Eq(propertyName, default(T)), Filter.Eq(propertyName, string.Empty), Filter.Eq(propertyName, new T[0])));

            case FilterOperator.StartsWith:
                return(Filter.Regex(propertyName, BuildRegex(nodeIn, s => "^" + s)));

            case FilterOperator.Contains:
                return(Filter.Regex(propertyName, BuildRegex(nodeIn, s => s)));

            case FilterOperator.EndsWith:
                return(Filter.Regex(propertyName, BuildRegex(nodeIn, s => s + "$")));

            case FilterOperator.Equals:
                return(Filter.Eq(propertyName, nodeIn.Rhs.Value));

            case FilterOperator.GreaterThan:
                return(Filter.Gt(propertyName, nodeIn.Rhs.Value));

            case FilterOperator.GreaterThanOrEqual:
                return(Filter.Gte(propertyName, nodeIn.Rhs.Value));

            case FilterOperator.LessThan:
                return(Filter.Lt(propertyName, nodeIn.Rhs.Value));

            case FilterOperator.LessThanOrEqual:
                return(Filter.Lte(propertyName, nodeIn.Rhs.Value));

            case FilterOperator.NotEquals:
                return(Filter.Ne(propertyName, nodeIn.Rhs.Value));

            case FilterOperator.In:
                return(Filter.In(propertyName, ((IList)nodeIn.Rhs.Value).OfType <object>()));
            }

            throw new NotSupportedException();
        }
Ejemplo n.º 19
0
        public FilterDefinition <T> GetFromCompareType <T>(FilterCondition s)
        {
            FilterDefinitionBuilder <T> filter = Builders <T> .Filter;

            if (s.Value == null)
            {
                return(filter.Empty);
            }

            switch (s.CompareType)
            {
            case TableCompareType.EQ:
                return(filter.Eq(s.Key, s.Value));

            case TableCompareType.GT:
                return(filter.Gt(s.Key, s.Value));

            case TableCompareType.GTE:
                return(filter.Gte(s.Key, s.Value));

            case TableCompareType.LT:
                return(filter.Lt(s.Key, s.Value));

            case TableCompareType.LTE:
                return(filter.Lte(s.Key, s.Value));

            case TableCompareType.NE:
                return(filter.Ne(s.Key, s.Value));

            case TableCompareType.REGEX:
            {
                return(filter.Regex(s.Key, s.Value.ToString()));
            }

            case TableCompareType.TEXT:
                return(filter.Text(s.Value.ToString()));

            default:
                return(filter.Eq(s.Key, s.Value));
            }
        }
Ejemplo n.º 20
0
        static void ExecuteAggregationQuery(DateRange dr)
        {
            FilterDefinitionBuilder <BsonDocument>
                matchFilterDefinition = Builders <BsonDocument> .Filter;
            var filter = matchFilterDefinition.Eq("event_type", "Address_Contact_Change_Request_Event") &
                         matchFilterDefinition.Gt("request_status_isodate", dr.Begin.ToString("o", CultureInfo.InvariantCulture)) &
                         matchFilterDefinition.Lt("request_status_isodate", dr.End.ToString("o", CultureInfo.InvariantCulture));

            var matchFilter    = BsonDocument.Parse("{\"event_type\":\"Address_Contact_Change_Request_Event\",\"request_status_isodate\":{$ne:null}}");
            var sortFilter     = BsonDocument.Parse("{\"request_status_isodate\":-1}");
            var groupByFilter  = BsonDocument.Parse("{\"_id\":{\"agreement_id\":\"$agreement_id\"},\"events\":{ \"$push\":{ \"event\":\"$$CURRENT\"} }}");
            var projectOp      = BsonDocument.Parse("{\"events\":{\"$slice\":[\"$events\",1]}}");
            var finalProjectOp = BsonDocument.Parse("{\"_id\":0,\"data\":\"$events.event\"}");
            var docs           = aggCollection
                                 .Aggregate()
                                 .Match(filter)
                                 .Sort(sortFilter)
                                 .Group(groupByFilter)
                                 .Project(projectOp)
                                 .Unwind("events")
                                 .Project(finalProjectOp)
                                 .ToList();
        }
Ejemplo n.º 21
0
        public override FilterDefinition <MongoContentEntity> Visit(BinaryOperatorNode nodeIn)
        {
            if (nodeIn.OperatorKind == BinaryOperatorKind.And)
            {
                return(Filter.And(nodeIn.Left.Accept(this), nodeIn.Right.Accept(this)));
            }
            if (nodeIn.OperatorKind == BinaryOperatorKind.Or)
            {
                return(Filter.Or(nodeIn.Left.Accept(this), nodeIn.Right.Accept(this)));
            }
            if (nodeIn.OperatorKind == BinaryOperatorKind.NotEqual)
            {
                return(Filter.Ne(BuildFieldDefinition(nodeIn.Left), BuildValue(nodeIn.Right)));
            }
            if (nodeIn.OperatorKind == BinaryOperatorKind.Equal)
            {
                return(Filter.Eq(BuildFieldDefinition(nodeIn.Left), BuildValue(nodeIn.Right)));
            }
            if (nodeIn.OperatorKind == BinaryOperatorKind.LessThan)
            {
                return(Filter.Lt(BuildFieldDefinition(nodeIn.Left), BuildValue(nodeIn.Right)));
            }
            if (nodeIn.OperatorKind == BinaryOperatorKind.LessThanOrEqual)
            {
                return(Filter.Lte(BuildFieldDefinition(nodeIn.Left), BuildValue(nodeIn.Right)));
            }
            if (nodeIn.OperatorKind == BinaryOperatorKind.GreaterThan)
            {
                return(Filter.Gt(BuildFieldDefinition(nodeIn.Left), BuildValue(nodeIn.Right)));
            }
            if (nodeIn.OperatorKind == BinaryOperatorKind.GreaterThanOrEqual)
            {
                return(Filter.Gte(BuildFieldDefinition(nodeIn.Left), BuildValue(nodeIn.Right)));
            }

            throw new NotSupportedException();
        }
Ejemplo n.º 22
0
        public void Gt_with_field_name_should_render_correctly(int?value, string expectedFilter)
        {
            var filter = __subject.Gt("I", value);

            filter.Render(__serializer, __registry).Should().Be(expectedFilter);
        }
Ejemplo n.º 23
0
        public async Task <List <BsonDocument> > Query()
        {
            IMongoCollection <BsonDocument>        coll          = GetCollection <BsonDocument>(DbName, CollName);
            FilterDefinitionBuilder <BsonDocument> filterBuilder = Builders <BsonDocument> .Filter;
            FilterDefinition <BsonDocument>        filter        = filterBuilder.Eq("name", "MongoDB") & filterBuilder.Gt("count", 1);

            return(await coll.Find(filter).ToListAsync());
        }
Ejemplo n.º 24
0
        private async Task <IEnumerable <T> > FetchEntities <T>
        (
            string metaPhrase,
            ProjectionDefinition <T> projection,
            IMongoCollection <T> collection,
            double daysTolerance,
            int limit,
            GeoJsonPoint <GeoJson3DGeographicCoordinates> targetPosition = null
        ) where T : IIdentifiable <ObjectId>, ILocatable, IMetaScored
        {
            var referenceDate = DateTime.UtcNow;

            var filterBuilder = new FilterDefinitionBuilder <T>();
            var filter        = filterBuilder.And
                                (
                filterBuilder.Gt
                (
                    post => post._id,
                    new ObjectId(referenceDate.Subtract(TimeSpan.FromDays(daysTolerance)), 0, 0, 0)
                ),
                filterBuilder.Or
                (
                    filterBuilder.Text(metaPhrase, new TextSearchOptions
            {
                CaseSensitive      = false,
                DiacriticSensitive = false,
            })
                    ,
                    filterBuilder.Exists(p => p._id)
                )
                                );

            var sortBuilder = new SortDefinitionBuilder <T>();
            var sort        = sortBuilder.Combine
                              (
                sortBuilder.MetaTextScore("metaScore"),
                sortBuilder.Descending(p => p._id)
                              );

            var cursor = await collection.FindAsync(filter, new FindOptions <T>
            {
                AllowPartialResults = true,
                Limit      = limit,
                Sort       = sort,
                Projection = projection
            });

            var enumerable = cursor.ToEnumerable();

            if (targetPosition != null)
            {
                enumerable = enumerable.OrderBy
                             (
                    item =>
                    item.Position.Coordinates.ToGeoCoordinate().GetDistanceTo(targetPosition.Coordinates.ToGeoCoordinate())
                    -
                    Math.Pow(item.MetaScore, 2)
                             );
            }

            return(enumerable);
        }
Ejemplo n.º 25
0
 //
 // 摘要:
 //     Tests that the value of the named element is greater than some value (see $gt).
 //
 // 参数:
 //   name:
 //     The name of the element to test.
 //
 //   value:
 //     The value to compare to.
 //
 // 返回结果:
 //     The builder (so method calls can be chained).
 public static FilterDefinition <BsonDocument> GT(string name, BsonValue value)
 {
     return(filter.Gt(name, value));
 }
Ejemplo n.º 26
0
        public override FilterDefinition <MongoContentEntity> Visit(BinaryOperatorNode nodeIn)
        {
            if (nodeIn.OperatorKind == BinaryOperatorKind.And)
            {
                return(Filter.And(nodeIn.Left.Accept(this), nodeIn.Right.Accept(this)));
            }

            if (nodeIn.OperatorKind == BinaryOperatorKind.Or)
            {
                return(Filter.Or(nodeIn.Left.Accept(this), nodeIn.Right.Accept(this)));
            }

            if (nodeIn.Left is SingleValueFunctionCallNode functionNode)
            {
                var regexFilter = Visit(functionNode);

                var value = BuildValue(nodeIn.Right);

                if (value is bool booleanRight)
                {
                    if ((nodeIn.OperatorKind == BinaryOperatorKind.Equal && !booleanRight) ||
                        (nodeIn.OperatorKind == BinaryOperatorKind.NotEqual && booleanRight))
                    {
                        regexFilter = Filter.Not(regexFilter);
                    }

                    return(regexFilter);
                }
            }
            else
            {
                if (nodeIn.OperatorKind == BinaryOperatorKind.NotEqual)
                {
                    var field = BuildFieldDefinition(nodeIn.Left);

                    return(Filter.Or(
                               Filter.Not(Filter.Exists(field)),
                               Filter.Ne(field, BuildValue(nodeIn.Right))));
                }

                if (nodeIn.OperatorKind == BinaryOperatorKind.Equal)
                {
                    return(Filter.Eq(BuildFieldDefinition(nodeIn.Left), BuildValue(nodeIn.Right)));
                }

                if (nodeIn.OperatorKind == BinaryOperatorKind.LessThan)
                {
                    return(Filter.Lt(BuildFieldDefinition(nodeIn.Left), BuildValue(nodeIn.Right)));
                }

                if (nodeIn.OperatorKind == BinaryOperatorKind.LessThanOrEqual)
                {
                    return(Filter.Lte(BuildFieldDefinition(nodeIn.Left), BuildValue(nodeIn.Right)));
                }

                if (nodeIn.OperatorKind == BinaryOperatorKind.GreaterThan)
                {
                    return(Filter.Gt(BuildFieldDefinition(nodeIn.Left), BuildValue(nodeIn.Right)));
                }

                if (nodeIn.OperatorKind == BinaryOperatorKind.GreaterThanOrEqual)
                {
                    return(Filter.Gte(BuildFieldDefinition(nodeIn.Left), BuildValue(nodeIn.Right)));
                }
            }

            throw new NotSupportedException();
        }
Ejemplo n.º 27
0
        /* 输入:设备Id、起止时间
         * 输出:总告警次数
         */
        public int GetDeviceAffiliateAlarmInfoNumber(String deviceId, DateTime startTime, DateTime endTime)
        {
            FilterDefinitionBuilder <AlarmInfoModel> builderFilter = Builders <AlarmInfoModel> .Filter;
            FilterDefinition <AlarmInfoModel>        filter        = builderFilter.And(builderFilter.Eq("DeviceId", deviceId),
                                                                                       builderFilter.Gt("Timestamp", startTime),
                                                                                       builderFilter.Lt("Timestamp", endTime));

            return((int)_alarmInfo.Find(filter).CountDocuments());

            /*
             * return _alarmInfo.AsQueryable()
             *  .Where(ai => ai.DeviceId == deviceId & ai.Timestamp>=startTime &ai.Timestamp<=endTime)
             *  .ToList().Count;
             */
        }
Ejemplo n.º 28
0
 public object Gt <TProperty>(string property, TProperty value)
 {
     return(InternalBuilder.Gt(property, value));
 }
Ejemplo n.º 29
0
 /// <inheritdoc/>
 public Task <CommittedAggregateEvents> FetchForAggregateAfter(EventSourceId eventSource, ArtifactId aggregateRoot, AggregateRootVersion after, CancellationToken cancellationToken)
 => DoFetchForAggregate(
     eventSource,
     aggregateRoot,
     defaultFilter => defaultFilter & _eventFilter.Gt(_ => _.Aggregate.Version, after.Value),
     cancellationToken);