Ejemplo n.º 1
0
        public void Count_should_include_the_filter(
            [Values(false, true)] bool async)
        {
            var subject = CreateSubject();
            var options = new CountOptions();

            if (async)
            {
#pragma warning disable 618
                subject.CountAsync(_providedFilter, options, CancellationToken.None);

                _mockDerivedCollection.Verify(
                    c => c.CountAsync(
                        It.Is <FilterDefinition <B> >(f => RenderFilter(f).Equals(_expectedFilter)),
                        options,
                        CancellationToken.None),
                    Times.Once);
#pragma warning restore
            }
            else
            {
#pragma warning disable 618
                subject.Count(_providedFilter, options, CancellationToken.None);

                _mockDerivedCollection.Verify(
                    c => c.Count(
                        It.Is <FilterDefinition <B> >(f => RenderFilter(f).Equals(_expectedFilter)),
                        options,
                        CancellationToken.None),
                    Times.Once);
#pragma warning restore
            }
        }
        public UnifiedCountDocumentsOperation Build(string targetCollectionId, BsonDocument arguments)
        {
            var collection = _entityMap.GetCollection(targetCollectionId);

            FilterDefinition <BsonDocument> filter = null;
            CountOptions         options           = null;
            IClientSessionHandle session           = null;

            foreach (var argument in arguments)
            {
                switch (argument.Name)
                {
                case "comment":
                    options ??= new CountOptions();
                    options.Comment = argument.Value;
                    break;

                case "filter":
                    filter = new BsonDocumentFilterDefinition <BsonDocument>(argument.Value.AsBsonDocument);
                    break;

                case "session":
                    session = _entityMap.GetSession(argument.Value.AsString);
                    break;

                default:
                    throw new FormatException($"Invalid CountDocumentsOperation argument name: '{argument.Name}'.");
                }
            }

            return(new UnifiedCountDocumentsOperation(collection, filter, options, session));
        }
Ejemplo n.º 3
0
 /// <summary>
 /// 获取总数
 /// </summary>
 /// <param name="collectionName"></param>
 /// <param name="filter"></param>
 /// <param name="options"></param>
 /// <returns></returns>
 public long Count(string collectionName, FilterDefinition <T> filter, CountOptions options = null)
 {
     return(infrastructure.Exec(database =>
     {
         return database.GetCollection <T>(collectionName).CountDocuments(filter, options);
     }));
 }
Ejemplo n.º 4
0
        public void Count_should_include_the_filter(
            [Values(false, true)] bool async)
        {
            var subject = CreateSubject();
            var options = new CountOptions();

            if (async)
            {
                subject.CountAsync(_providedFilter, options, CancellationToken.None);

                _derivedCollection.Received().CountAsync(
                    Arg.Is <FilterDefinition <B> >(f => RenderFilter(f).Equals(_expectedFilter)),
                    options,
                    CancellationToken.None);
            }
            else
            {
                subject.Count(_providedFilter, options, CancellationToken.None);

                _derivedCollection.Received().Count(
                    Arg.Is <FilterDefinition <B> >(f => RenderFilter(f).Equals(_expectedFilter)),
                    options,
                    CancellationToken.None);
            }
        }
Ejemplo n.º 5
0
        public async Task<bool> Exists(Expression<Func<T, bool>> expression)
        {
            var options = new CountOptions { Limit = 1 };

            long count = await _context.Collection.CountDocumentsAsync(_session?.Handle, expression, options);

            return count != 0;
        }
Ejemplo n.º 6
0
        public async Task<bool> Exists(params Guid[] ids)
        {
            var filter = StorageUtils.BuildIdsFilter<T>(ids);
            var options = new CountOptions { Limit = 1 };

            long count = await _context.Collection.CountDocumentsAsync(_session?.Handle, filter, options);

            return count != 0;
        }
 public UnifiedCountDocumentsOperation(
     IMongoCollection <BsonDocument> collection,
     FilterDefinition <BsonDocument> filter,
     CountOptions options)
 {
     _collection = collection;
     _filter     = filter;
     _options    = options;
 }
        /// <summary>
        /// 数量
        /// </summary>
        /// <param name="filter"></param>
        /// <param name="limit"></param>
        /// <param name="skip"></param>
        /// <param name="hint">hint索引</param>
        /// <param name="readPreference">访问设置</param>
        /// <returns></returns>
        public Task <long> CountAsync(FilterDefinition <TEntity> filter, int limit = 0, int skip = 0, BsonValue hint = null, ReadPreference readPreference = null)
        {
            if (filter == null)
            {
                filter = Builders <TEntity> .Filter.Empty;
            }
            CountOptions options = base.CreateCountOptions(limit, skip, hint);

            return(base.GetCollection(readPreference).CountAsync(filter, options, default(CancellationToken)));
        }
 /// <summary>
 ///
 /// </summary>
 /// <typeparam name="TForeign">文档类型</typeparam>
 /// <typeparam name="T">文档类型</typeparam>
 /// <param name="foreignDocument">文档对象</param>
 /// <param name="filter">过滤器</param>
 /// <param name="options">设置</param>
 /// <param name="cancellationToken">标记</param>
 /// <returns></returns>
 public long DynamicCollectionCountDocuments <TForeign, T>(
     TForeign foreignDocument,
     Expression <Func <T, bool> > filter,
     CountOptions options = null,
     CancellationToken cancellationToken = default)
     where TForeign : BaseMongoEntity
     where T : BaseMongoEntity
 {
     return(Database.GetCollection <T>($"{typeof(T).Name}_{foreignDocument.Id}").CountDocuments(filter, options, cancellationToken));
 }
Ejemplo n.º 10
0
        public Task <long> CountAsync(FilterDefinition <TEntity> filter, int limit = 0, int skip = 0, BsonValue hint = null, ReadPreference readPreference = null)
        {
            if (filter == null)
            {
                filter = Filter.Empty;
            }
            CountOptions options = CreateCountOptions(limit, skip, hint);

            return(GetCollection(readPreference).CountAsync(filter, options));
        }
 /// <summary>
 ///
 /// </summary>
 /// <typeparam name="TForeign">文档类型</typeparam>
 /// <typeparam name="T">文档类型</typeparam>
 /// <param name="foreignDocument">文档对象</param>
 /// <param name="filter">Lambda过滤器</param>
 /// <param name="options">设置</param>
 /// <param name="cancellationToken">标记</param>
 /// <returns></returns>
 public Task <long> DynamicCollectionCountDocumentsAsync <TForeign, T>(
     TForeign foreignDocument,
     Expression <Func <T, bool> > filter,
     CountOptions options = null,
     CancellationToken cancellationToken = default)
     where TForeign : BaseMongoEntity
     where T : BaseMongoEntity
 {
     return(Task.Run(() => DynamicCollectionCountDocuments(foreignDocument, filter, options, cancellationToken)));
 }
 /// <summary>
 ///
 /// </summary>
 /// <typeparam name="TForeign">文档类型</typeparam>
 /// <typeparam name="T">文档类型</typeparam>
 /// <param name="session">会话句柄(作用于事务)</param>
 /// <param name="foreignDocument">文档对象</param>
 /// <param name="filter">过滤器</param>
 /// <param name="options">设置</param>
 /// <param name="cancellationToken">标记</param>
 /// <returns></returns>
 public long DynamicCollectionCountDocuments <TForeign, T>(
     IClientSessionHandle session,
     TForeign foreignDocument,
     FilterDefinition <T> filter,
     CountOptions options = null,
     CancellationToken cancellationToken = default)
     where TForeign : BaseMongoEntity
     where T : BaseMongoEntity
 {
     return(Database.GetCollection <T>($"{typeof(T).Name}_{foreignDocument.Id}").CountDocuments(session, filter, options, cancellationToken));
 }
 public UnifiedCountDocumentsOperation(
     IMongoCollection <BsonDocument> collection,
     FilterDefinition <BsonDocument> filter,
     CountOptions options,
     IClientSessionHandle session)
 {
     _collection = collection;
     _filter     = filter;
     _options    = options;
     _session    = session;
 }
 /// <summary>
 ///
 /// </summary>
 /// <typeparam name="TForeign">文档类型</typeparam>
 /// <typeparam name="T">文档类型</typeparam>
 /// <param name="foreignDocument">文档对象</param>
 /// <param name="session">客户端会话句柄</param>
 /// <param name="filter">过滤器</param>
 /// <param name="options">设置</param>
 /// <param name="cancellationToken">标记</param>
 /// <returns></returns>
 public Task <long> DynamicCollectionCountDocumentsAsync <TForeign, T>(
     IClientSessionHandle session,
     TForeign foreignDocument,
     FilterDefinition <T> filter,
     CountOptions options = null,
     CancellationToken cancellationToken = default)
     where TForeign : BaseMongoEntity
     where T : BaseMongoEntity
 {
     return(Task.Run(() => DynamicCollectionCountDocuments(session, foreignDocument, filter, options, cancellationToken)));
 }
Ejemplo n.º 15
0
        static void Main()
        {
            bool repeat = true;

            do
            {
                MainMenu();
                CountOptions OptionNumber = TryReadOption();

                Console.Clear();
                Console.WriteLine(" === Расчёт площади фигуры === \n");

                switch (OptionNumber)
                {
                case CountOptions.Circle:
                    Console.Write(" Введите радиус круга: ");
                    var radius = TryReadDouble();
                    var circle = new Circle(radius);

                    PrintAnswer(circle.CountArea());
                    ReturnToMainMenu();
                    break;

                case CountOptions.Rectangle:
                    Console.Write(" Введите длину прямоугольника: ");
                    var width = TryReadDouble();
                    Console.Write(" Введите ширину прямоугольника: ");
                    var height    = TryReadDouble();
                    var rectangle = new Rectangle(width, height);

                    PrintAnswer(rectangle.CountArea());
                    ReturnToMainMenu();
                    break;

                case CountOptions.Triangle:
                    Console.Write(" Введите основание треугольника: ");
                    var triangleBase = TryReadDouble();
                    Console.Write(" Введите высоту треугольника: ");
                    var triangleHeight = TryReadDouble();

                    var triangle = new Triangle(triangleBase, triangleHeight);

                    PrintAnswer(triangle.CountArea());

                    ReturnToMainMenu();
                    break;

                case CountOptions.Quit:
                    repeat = false;
                    break;
                }
            } while (repeat);
        }
Ejemplo n.º 16
0
        public int GetCount(DataBaseContext context, BsonDocument filter, CountOptions options = null)
        {
            if (!MongoClients.ContainsKey(context.ClientKey))
            {
                throw new NullReferenceException("请先连接MongoDB!");
            }

            var collection = MongoClients[context.ClientKey].GetDatabase(context.DbName).GetCollection <BsonDocument>(context.CollectionName);
            var count      = collection.CountDocuments(filter, options);

            return((int)count);
        }
Ejemplo n.º 17
0
        Task <long> ICollectionAdapter <TEntity> .CountAsync(
            Expression <Func <TEntity, bool> > filter,
            CountOptions options,
            CancellationToken token)
        {
            if (filter == null)
            {
                return(this.collection.CountAsync(new BsonDocument(), options, token));
            }

            return(this.collection.CountAsync(filter, options, token));
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Returns the number of items of the requested type in the Mongo collection filtered by the given expression.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public long Count <T>(Expression <Func <T, bool> > expression, Collation collation = null) where T : DataEntityBase
        {
            CountOptions countOptions = new CountOptions()
            {
                Collation = collation
            };

            Logger.Trace($"{nameof(MongoStore)}.{nameof(Count)}",
                         new LogItem("Event", "Get collection count"), new LogItem("Type", typeof(T).ToString),
                         new LogItem("Expression", expression.ToString));
            return(GetCollection <T>().Count(expression, countOptions));
        }
Ejemplo n.º 19
0
        public void CountTest()
        {
            // Arrange
            var items        = new int[] { 3, 4, 2 };
            var countOptions = new CountOptions();

            // Act
            ConzoleUtils.Count(items);

            // Assert
            mockConsole.Verify(c => c.WriteLine(countOptions.ResultFormatter(items.Length)));
            mockConsole.Verify(c => c.WriteLine(), Times.Once);
        }
Ejemplo n.º 20
0
        public void CountCustomFormatTest()
        {
            // Arrange
            var items        = new int[] { 3, 4, 2 };
            var countOptions = new CountOptions();

            countOptions.PostNewLine     = false;
            countOptions.ResultFormatter = count => $"aaa {count} bbb";

            // Act
            ConzoleUtils.Count(items, countOptions);

            // Assert
            mockConsole.Verify(c => c.WriteLine(countOptions.ResultFormatter(items.Length)));
            mockConsole.Verify(c => c.WriteLine(), Times.Never);
        }
Ejemplo n.º 21
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="limit"></param>
        /// <param name="skip"></param>
        /// <param name="hint"></param>
        /// <returns></returns>
        public CountOptions CreateCountOptions(int skip = 0, BsonValue hint = null)
        {
            CountOptions option = new CountOptions();

            if (skip > 0)
            {
                option.Skip = skip;
            }

            if (hint != null)
            {
                option.Hint = hint;
            }

            return(option);
        }
Ejemplo n.º 22
0
    private static async Task <bool> IsCollEmpty(IMongoCollection <LeaderBoardSchema> collection) //Checks if there is at least one doc present in collection
    {                                                                                             //TODO: Can this method be modified to check game state collection as well?
        var docType      = FilterDefinition <LeaderBoardSchema> .Empty;
        var countOptions = new CountOptions {
            MaxTime = timeOut
        };
        var collIsEmpty = true;

        if (await collection.CountDocumentsAsync(docType, countOptions) > 0)
        {
            Debug.Log($"<Color=blue>Attention</color> Collection {collection.GetType()} is NOT empty");
            collIsEmpty = false;
        }

        Debug.Log($"<Color=blue>Attention</color> {nameof(IsCollEmpty)}() Returning {collIsEmpty}.");
        return(collIsEmpty);
    }
Ejemplo n.º 23
0
        /// <summary>
        /// Get the number of children for a relationship
        /// </summary>
        /// <param name="session">An optional session if using within a transaction</param>
        /// <param name="options">An optional AggregateOptions object</param>
        /// <param name="cancellation">An optional cancellation token</param>
        public Task <long> ChildrenCountAsync(IClientSessionHandle session = null, CountOptions options = null, CancellationToken cancellation = default)
        {
            parent.ThrowIfUnsaved();

            if (isInverse)
            {
                return(session == null
                       ? JoinCollection.CountDocumentsAsync(j => j.ChildID == parent.ID, options, cancellation)
                       : JoinCollection.CountDocumentsAsync(session, j => j.ChildID == parent.ID, options, cancellation));
            }
            else
            {
                return(session == null
                       ? JoinCollection.CountDocumentsAsync(j => j.ParentID == parent.ID, options, cancellation)
                       : JoinCollection.CountDocumentsAsync(session, j => j.ParentID == parent.ID, options, cancellation));
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="limit"></param>
        /// <param name="skip"></param>
        /// <param name="hint"></param>
        /// <returns></returns>
        public CountOptions CreateCountOptions(int limit = 0, int skip = 0, BsonValue hint = null)
        {
            CountOptions countOptions = new CountOptions();

            if (limit > 0)
            {
                countOptions.Limit = new long?((long)limit);
            }
            if (skip > 0)
            {
                countOptions.Skip = new long?((long)skip);
            }
            if (hint != null)
            {
                countOptions.Hint = hint;
            }
            return(countOptions);
        }
Ejemplo n.º 25
0
        public CountOptions CreateCountOptions(int limit = 0, int skip = 0, BsonValue hint = null)
        {
            CountOptions options = new CountOptions();

            if (limit > 0)
            {
                options.Limit = limit;
            }
            if (skip > 0)
            {
                options.Skip = skip;
            }
            if (hint != null)
            {
                options.Hint = hint;
            }
            return(options);
        }
Ejemplo n.º 26
0
        public static long MyCount(this IMongoCollection <BsonDocument> collection, IClientSessionHandle session, FilterDefinition <BsonDocument> filter, long skip, long first)
        {
            if (skip <= 0 && first <= 0)
            {
                return(collection.CountDocuments(session, filter));
            }

            var options = new CountOptions();

            if (skip > 0)
            {
                options.Skip = skip;
            }
            if (first > 0)
            {
                options.Limit = first;
            }

            return(collection.CountDocuments(session, filter, options));
        }
        public long Count(FilterDefinition <T> filter, CountOptions option = null)
        {
            var database        = client.GetDatabase(DatabaseName);
            var myCollection    = database.GetCollection <T>(collectionName);
            var aggregateResult = myCollection.Aggregate().Match(filter).Group(new BsonDocument()
            {
                { "_id", "null" },
                { "count", new BsonDocument("$sum", 1) }
            });
            var results = aggregateResult.ToListAsync().GetAwaiter().GetResult();

            if (results.Count == 1)
            {
                return(Convert.ToInt64(results[0].GetElement("count").Value));
            }
            else
            {
                return(0);
            }
        }
Ejemplo n.º 28
0
    private static async Task <bool> IsDocumentPresent(string _id, IMongoCollection <LeaderBoardSchema> collection)//TODO: Modify this to check for Game State docs
    {
        LeaderBoardSchema docFound = null;
        var docType      = FilterDefinition <LeaderBoardSchema> .Empty;
        var countOptions = new CountOptions {
            MaxTime = timeOut
        };
        var newProjection = Builders <LeaderBoardSchema> .Projection.Exclude(x => x.list);

        var searchOptions = new FindOptions <LeaderBoardSchema> {
            Limit = 1, MaxAwaitTime = timeOut, Projection = newProjection
        };
        var searchFilter = Builders <LeaderBoardSchema> .Filter.Eq("_id", _id);


        if (await collection.CountDocumentsAsync(docType, countOptions) > 0)
        {
            using (IAsyncCursor <LeaderBoardSchema> cursor = await collection.FindAsync(searchFilter, searchOptions))
            {
                while (await cursor.MoveNextAsync())
                {
                    IEnumerable <LeaderBoardSchema> batch = cursor.Current;

                    foreach (LeaderBoardSchema document in batch)
                    {
                        docFound = document;
                        Debug.Log($"isDocPresent: {document}");
                    }
                }
            }

            Debug.Log($"<Color=blue>Attention</color> docFound {docFound}");

            return((docFound != null) ? true: false);
        }

        Debug.Log($"<Color=red>Attention</color> Collection {collection.ToString()} is empty. Returning false.");
        return(false);
    }
        public UnifiedCountDocumentsOperation Build(string targetCollectionId, BsonDocument arguments)
        {
            var collection = _entityMap.GetCollection(targetCollectionId);

            FilterDefinition <BsonDocument> filter = null;
            CountOptions options = null;

            foreach (var argument in arguments)
            {
                switch (argument.Name)
                {
                case "filter":
                    filter = new BsonDocumentFilterDefinition <BsonDocument>(argument.Value.AsBsonDocument);
                    break;

                default:
                    throw new FormatException($"Invalid CountDocumentsOperation argument name: '{argument.Name}'.");
                }
            }

            return(new UnifiedCountDocumentsOperation(collection, filter, options));
        }
Ejemplo n.º 30
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="collectionName"></param>
        /// <param name="filter"></param>
        /// <param name="options"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task <long> CountAsync <TDocument>(string collectionName, FilterDefinition <TDocument> filter, CountOptions options = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            var collection = this.GetMongoCollection <TDocument>(collectionName);

            return(await collection.CountAsync(filter, options, cancellationToken));
        }