Exemplo n.º 1
0
 public abstract void CreateView <TDocument, TResult>(String viewName, String viewOn, PipelineDefinition <TDocument, TResult> pipeline, CreateViewOptions <TDocument> options = null, CancellationToken cancellationToken = default(CancellationToken));
Exemplo n.º 2
0
 /// <inheritdoc/>
 public Task <IAsyncCursor <TResult> > WatchAsync <TResult>(IClientSessionHandle session, PipelineDefinition <ChangeStreamDocument <T>, TResult> pipeline, ChangeStreamOptions options = null, CancellationToken cancellationToken = default(CancellationToken))
 {
     throw new System.NotImplementedException();
 }
Exemplo n.º 3
0
        private RenderedPipelineDefinition <TOutput> RenderPipeline <TInput, TOutput>(PipelineDefinition <TInput, TOutput> pipeline)
        {
            var serializerRegistry = BsonSerializer.SerializerRegistry;
            var inputSerializer    = serializerRegistry.GetSerializer <TInput>();

            return(pipeline.Render(inputSerializer, serializerRegistry));
        }
Exemplo n.º 4
0
 /// <inheritdoc/>
 public Task <IAsyncCursor <TResult> > AggregateAsync <TResult>(IClientSessionHandle session, PipelineDefinition <T, TResult> pipeline, AggregateOptions options = null, CancellationToken cancellationToken = default)
 {
     return(_actualCollection.AggregateAsync(session, pipeline, options, cancellationToken));
 }
Exemplo n.º 5
0
 /// <inheritdoc/>
 public Task <IAsyncCursor <TResult> > AggregateAsync <TResult>(IClientSessionHandle session, PipelineDefinition <T, TResult> pipeline, AggregateOptions options = null, CancellationToken cancellationToken = default(CancellationToken))
 {
     throw new System.NotImplementedException();
 }
Exemplo n.º 6
0
        public static TResult Iterate <TSource, TResult>(IMongoCollection <TSource> collection, PipelineDefinition <TSource, BsonDocument> pipeline, Func <BsonDocument, TResult, TResult> callback)
        {
            var docCursor = collection.Aggregate(pipeline);

            TResult value = default(TResult);

            while (docCursor.MoveNext())
            {
                var doc = docCursor.Current;
                foreach (var item in doc)
                {
                    value = callback.Invoke(item, value);
                }
            }
            return(value);
        }
Exemplo n.º 7
0
 /// <inheritdoc/>
 public Task <IAsyncCursor <TResult> > WatchAsync <TResult>(IClientSessionHandle session, PipelineDefinition <ChangeStreamDocument <T>, TResult> pipeline, ChangeStreamOptions options = null, CancellationToken cancellationToken = default)
 {
     return(_actualCollection.WatchAsync(session, pipeline, options, cancellationToken));
 }
Exemplo n.º 8
0
 public void Aggregate(PipelineDefinition <T, BsonDocument> pipeline) => Collection.AggregateToCollection(pipeline);
Exemplo n.º 9
0
 public Task <IAsyncCursor <TResult> > AggregateAsync <TResult>(PipelineDefinition <TDocument, TResult> pipeline, AggregateOptions options = null, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(Task.FromResult(Aggregate(pipeline, options, cancellationToken)));
 }
Exemplo n.º 10
0
 public void CreateView <TDocument, TResult>(string viewName, string viewOn, PipelineDefinition <TDocument, TResult> pipeline, CreateViewOptions <TDocument> options = null, CancellationToken cancellationToken = default(CancellationToken))
 {
     _database.CreateView(viewName, viewOn, pipeline, options, cancellationToken);
 }
Exemplo n.º 11
0
 public Task CreateViewAsync <TDocument, TResult>(IClientSessionHandle session, string viewName, string viewOn, PipelineDefinition <TDocument, TResult> pipeline, CreateViewOptions <TDocument> options = null, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(_database.CreateViewAsync(session, viewName, viewOn, pipeline, options, cancellationToken));
 }
Exemplo n.º 12
0
        private void ParseUpdateModel(
            BsonDocument model,
            out FilterDefinition <BsonDocument> filter,
            out UpdateDefinition <BsonDocument> update,
            out List <ArrayFilterDefinition> arrayFilters,
            out BsonValue hint,
            out bool isUpsert)
        {
            arrayFilters = null;
            filter       = null;
            update       = null;
            hint         = null;
            isUpsert     = false;

            foreach (BsonElement argument in model.Elements)
            {
                switch (argument.Name)
                {
                case "arrayFilters":
                    arrayFilters = argument
                                   .Value
                                   .AsBsonArray
                                   .Cast <BsonDocument>()
                                   .Select(x => new BsonDocumentArrayFilterDefinition <BsonValue>(x))
                                   .ToList <ArrayFilterDefinition>();
                    break;

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

                case "hint":
                    hint = argument.Value;
                    break;

                case "update":
                    switch (argument.Value)
                    {
                    case BsonDocument:
                        update = argument.Value.AsBsonDocument;
                        break;

                    case BsonArray:
                        update = PipelineDefinition <BsonDocument, BsonDocument> .Create(argument.Value.AsBsonArray.Cast <BsonDocument>());

                        break;

                    default:
                        throw new FormatException($"Invalid BulkWrite Update model update argument: '{argument.Value}'.");
                    }
                    break;

                case "upsert":
                    isUpsert = argument.Value.ToBoolean();
                    break;

                default:
                    throw new FormatException($"Invalid BulkWrite Update model argument name: '{argument.Name}'.");
                }
            }
        }
        // private methods
        private RenderedPipelineDefinition <ChangeStreamDocument <BsonDocument> > RenderPipeline(PipelineDefinition <ChangeStreamDocument <BsonDocument>, ChangeStreamDocument <BsonDocument> > pipeline)
        {
            var serializerRegistry = BsonSerializer.SerializerRegistry;
            var inputSerializer    = new ChangeStreamDocumentSerializer <BsonDocument>(BsonDocumentSerializer.Instance);

            return(pipeline.Render(inputSerializer, serializerRegistry));
        }
Exemplo n.º 14
0
 public Task CreateViewAsync <TDocument, TResult>(String viewName, String viewOn, PipelineDefinition <TDocument, TResult> pipeline, CreateViewOptions <TDocument> options = null, CancellationToken cancellationToken = default(CancellationToken))
 {
     CreateView(viewName, viewOn, pipeline, options, cancellationToken);
     return(Task.CompletedTask);
 }
Exemplo n.º 15
0
        // private methods
        private IList <BsonDocument> RenderStages <TInput, TOutput>(PipelineDefinition <TInput, TOutput> pipeline, IBsonSerializer <TInput> inputSerializer)
        {
            var renderedPipeline = pipeline.Render(inputSerializer, BsonSerializer.SerializerRegistry);

            return(renderedPipeline.Documents);
        }
Exemplo n.º 16
0
 public abstract IAsyncCursor <TResult> Aggregate <TResult>(PipelineDefinition <TDocument, TResult> pipeline, AggregateOptions options = null, CancellationToken cancellationToken = default(CancellationToken));
Exemplo n.º 17
0
 public IAsyncCursor <TResult> AsyncCursor <TDocument, TKey, TResult>(
     PipelineDefinition <TDocument, TResult> pipelineDefinition) where TDocument : AggregateRootWithId <TKey>
 {
     return(_dbContext.GetCollection <TDocument>().Aggregate(pipelineDefinition));
 }
Exemplo n.º 18
0
 /// <inheritdoc/>
 public Task CreateViewAsync <TDocument, TResult>(IClientSessionHandle session, string viewName, string viewOn, PipelineDefinition <TDocument, TResult> pipeline, CreateViewOptions <TDocument> options = null, CancellationToken cancellationToken = default)
 {
     throw new System.NotImplementedException();
 }
Exemplo n.º 19
0
 /// <inheritdoc/>
 public IAsyncCursor <TResult> Watch <TResult>(PipelineDefinition <ChangeStreamDocument <T>, TResult> pipeline, ChangeStreamOptions options = null, CancellationToken cancellationToken = default)
 {
     return(_actualCollection.Watch(pipeline, options, cancellationToken));
 }
Exemplo n.º 20
0
 /// <inheritdoc/>
 public void CreateView <TDocument, TResult>(string viewName, string viewOn, PipelineDefinition <TDocument, TResult> pipeline, CreateViewOptions <TDocument> options = null, CancellationToken cancellationToken = default)
 {
     throw new System.NotImplementedException();
 }
Exemplo n.º 21
0
 /// <inheritdoc/>
 public IAsyncCursor <TResult> Aggregate <TResult>(PipelineDefinition <T, TResult> pipeline, AggregateOptions options = null, CancellationToken cancellationToken = default)
 {
     return(_actualCollection.Aggregate(pipeline, options, cancellationToken));
 }
Exemplo n.º 22
0
        public async Task CountMovies()
        {
            // This stage finds all movies that have a specific director
            var matchStage = new BsonDocument("$match",
                                              new BsonDocument("directors", "Rob Reiner"));


            // This stage sorts the results by the number of reviews,
            // in descending order
            var sortStage = new BsonDocument("$sort",
                                             new BsonDocument("tomatoes.viewer.numReviews", -1));

            // This stage generates the projection we want
            var projectionStage = new BsonDocument("$project",
                                                   new BsonDocument
            {
                { "_id", 0 },
                { "Movie Title", "$title" },
                { "Year", "$year" },
                { "Average User Rating", "$tomatoes.viewer.rating" }
            });

            /* We now put the stages together in a pipeline. Note that a
             * pipeline definition requires us to specify the input and output
             * types. In this case, the input is of type Movie, but because
             * we are using a Projection with custom fields, our output is
             * a generic BsonDocument object. To be really cool, we could
             * create a mapping class for the output type, which is what we've
             * done for you in the MFlix application.
             */

            var pipeline = PipelineDefinition <Movie, BsonDocument>
                           .Create(new BsonDocument[] {
                matchStage,
                sortStage,
                projectionStage
            });


            var result = await _moviesCollection.Aggregate(pipeline).ToListAsync();

            /* Note: we're making a synchronous Aggregate() call.
             * If you want a challenge, change the line above to make an
             * asynchronous call (hint: you'll need to make 2 changes),
             * and then confirm the unit test still passes.
             */

            Assert.AreEqual(14, result.Count);
            var firstMovie = result[0];

            Assert.AreEqual("The Princess Bride", firstMovie.GetValue("Movie Title").AsString);
            Assert.AreEqual(1987, firstMovie.GetValue("Year").AsInt32);
            Assert.AreEqual(4.0, firstMovie.GetValue("Average User Rating").AsDouble);

            /* We specifically excluded the "Id" field in the projection stage
             * that we built in the code above, so let's make sure that field
             * wasn't included in the resulting BsonDocument. We expect the call
             * to GetValue() to throw a KeyNotFoundException exception if the
             * field doesn't exist.
             */

            Assert.Throws <KeyNotFoundException>(() => firstMovie.GetValue("Id"));
        }
Exemplo n.º 23
0
 /// <inheritdoc/>
 public IAsyncCursor <TResult> Aggregate <TResult>(PipelineDefinition <T, TResult> pipeline, AggregateOptions options = null, CancellationToken cancellationToken = default(CancellationToken))
 {
     throw new System.NotImplementedException();
 }
        private List <BsonDocument> RenderPipeline <TInput, TOutput>(PipelineDefinition <TInput, TOutput> pipeline)
        {
            var serializer = BsonSerializer.SerializerRegistry.GetSerializer <TInput>();

            return(pipeline.Render(serializer, BsonSerializer.SerializerRegistry).Documents.ToList());
        }
Exemplo n.º 25
0
 /// <inheritdoc/>
 public IAsyncCursor <TResult> Watch <TResult>(PipelineDefinition <ChangeStreamDocument <T>, TResult> pipeline, ChangeStreamOptions options = null, CancellationToken cancellationToken = default(CancellationToken))
 {
     throw new System.NotImplementedException();
 }
Exemplo n.º 26
0
 public Task <IAsyncCursor <TResult> > AggregateAsync <TResult>(PipelineDefinition <T, TResult> pipeline, AggregateOptions options = null, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(_Repository.AggregateAsync(pipeline, options, cancellationToken));
 }
 public IEnumerator <ChangeStreamDocument <ProfileEntity> > SubscribeToChangesMany(
     PipelineDefinition <ChangeStreamDocument <ProfileEntity>, ChangeStreamDocument <ProfileEntity> > pipeline
     )
 {
     return(_mongoRepository.SubscribeToChangesStreamMany(pipeline) !);
 }
Exemplo n.º 28
0
        public List <BsonDocument> Aggregate(string mongodbConnStr, string mongodbDatabase, string coll, PipelineDefinition <BsonDocument, BsonDocument> pipeline)
        {
            var client     = new MongoClient(mongodbConnStr);
            var database   = client.GetDatabase(mongodbDatabase);
            var collection = database.GetCollection <BsonDocument>(coll);
            var query      = collection.Aggregate(pipeline).ToList();

            client = null;
            return(query);
        }
        public void TestExpressionQueries(IMongoCollection <MongoItem> col, IMongoQueryable <MongoItem> query)
        {
            #region Various LINQ-Expressions to combine and test
            Expression <Func <MongoItem, bool> > cityExpressionVienna = (d => d.City == "Vienna");
            Expression <Func <MongoItem, bool> > cityExpressionGraz   = (d => d.City == "Graz");
            Expression <Func <MongoItem, bool> > firstNameExpression  = (d => d.DemoUser.FirstName == "Michaela");
            Expression <Func <MongoItem, bool> > firstNameExpression2 = (d => (d.DemoUser.FirstName == "Michaela" || d.City == "Graz"));
            Expression <Func <MongoItem, bool> > modeExpression       = (d => (d.Mode == "ModeA" || d.Mode == "ModeB" || d.Mode == "ModeC"));
            Expression <Func <MongoItem, bool> > modeExpression2      = (d => (d.Mode != "ModeA" && d.Mode != "ModeB" && d.Mode != "ModeC"));
            Expression <Func <MongoItem, bool> > modeExpression3      = (d => (d.Mode == "ModeA"));

            DateTimeOffset sFrom = DateTimeOffset.ParseExact("2017:04:02 18:00:00", "yyyy:MM:dd HH:mm:ss", null).ToUniversalTime();
            DateTimeOffset sTo   = DateTimeOffset.ParseExact("2017:04:03 15:59:00", "yyyy:MM:dd HH:mm:ss", null).ToUniversalTime();
            //Expression<Func<MongoItem, bool>> isWithinDateRange = (d => (d.CheckPoint.CompareTo(sFrom) >= 0 && d.CheckPoint.CompareTo(sTo) <= 0));
            Expression <Func <MongoItem, bool> > isWithinDateRange = (d => (d.CheckPointUTC.CompareTo(sFrom.ToString("u")) >= 0 && d.CheckPointUTC.CompareTo(sTo.ToString("u")) <= 0));

            Expression <Func <MongoItem, bool> > containsTagFemale = (d => d.TagList.Contains <string>("female"));
            Expression <Func <MongoItem, bool> > containsUserID    = (d => d.UserList.Contains <string>("martinau"));

            //Expression<Func<MongoItem, DateTimeOffset>> orderByDate = t => t.CheckPoint;
            Expression <Func <MongoItem, string> > orderByDate = t => t.CheckPointUTC;
            #endregion

            #region Build a LINQ-Query, turn it to JSON, create aggregate Pipeline with BSON from JSON
            PipelineDefinition <MongoItem, MongoItem> aggregatePipeline = null;
            // Build a more complex LINQ Query
            var query0 = query.Where(cityExpressionVienna).OrderBy("CheckPointUTC ASC").Skip(1).Take(2);
            // Use the overloaded toString()-method to retrieve the aggregate-query ==> "aggregate([{match-Expression},...])
            string mongoAggregateQueryString = query0.ToString();
            Regex  aggregateParameters       = new Regex(@"(aggregate\()(.*)(\)$)");
            mongoAggregateQueryString = aggregateParameters.Match(mongoAggregateQueryString).Groups[2].Value;
            List <BsonDocument> docs = new List <BsonDocument>();
            var aggElements          = BsonSerializer.Deserialize <BsonArray>(mongoAggregateQueryString);
            foreach (var el in aggElements)
            {
                docs.Add(el.AsBsonDocument);
            }
            aggregatePipeline = docs.ToArray <BsonDocument>();
            //Build a Pipeline out of multiple single Bson documents
            //BsonDocument matchBsonDoc = BsonDocument.Parse("{ \"$match\" : { \"City\" : \"Vienna\" } }");
            //aggregatePipeline = new BsonDocument[]
            //{
            //  matchBsonDoc,
            //  new BsonDocument { { "$sort", new BsonDocument("CheckPointUTC", 1) } }
            //};

            int assertCounter    = 0;
            var aggregateResults = col.Aggregate(aggregatePipeline);
            foreach (var item in aggregateResults.ToList <MongoItem>())
            {
                Console.WriteLine($"{item.DemoUser.FirstName} {item.DemoUser.LastName}");
                if (assertCounter == 0)
                {
                    Debug.Assert(item.DemoUser.FirstName == "Nina");
                }
                if (assertCounter == 0)
                {
                    Debug.Assert(item.DemoUser.LastName == "Huber");
                }
                if (assertCounter == 1)
                {
                    Debug.Assert(item.DemoUser.FirstName == "Michaela");
                }
                if (assertCounter == 1)
                {
                    Debug.Assert(item.DemoUser.LastName == "Bauer");
                }
                assertCounter++;
            }
            Debug.Assert(assertCounter == 2);
            #endregion

            var query1 = query.Where(cityExpressionVienna).OrderBy(orderByDate);
            var query2 = query.Where(cityExpressionVienna).OrderByDescending(orderByDate);

            var query3     = query.Where(cityExpressionVienna.AndAlso(modeExpression3));
            var query3Same = query.Where((d => d.City == "Vienna" && d.Mode == "ModeA"));

            var query4 = query.Where(cityExpressionVienna.AndAlso(containsTagFemale)).OrderBy(orderByDate);
            var query5 = query.Where(cityExpressionGraz.AndAlso(containsTagFemale).AndAlso(containsUserID)).OrderBy(orderByDate);
            var query6 = query.Where(cityExpressionVienna.AndAlso(isWithinDateRange)).OrderBy(orderByDate);

            List <MongoItem> queryResult = null;
            queryResult = query1.ToList <MongoItem>();
            queryResult.Assert(new string[] { "Andreas Pollak", "Nina Huber", "Michaela Bauer" });
            queryResult = query2.ToList <MongoItem>();
            queryResult.Assert(new string[] { "Michaela Bauer", "Nina Huber", "Andreas Pollak" });
            queryResult = query3.ToList <MongoItem>();
            queryResult.Assert(new string[] { "Andreas Pollak", "Nina Huber" });
            queryResult = query3Same.ToList <MongoItem>();
            queryResult.Assert(new string[] { "Andreas Pollak", "Nina Huber" });
            queryResult = query6.ToList <MongoItem>();
            queryResult.Assert(new string[] { "Andreas Pollak", "Nina Huber" });

            // Folgende Queries können nicht über die CosmosDB ausgeführt werden!!
            // {aggregate([{ "$match" : { "TagList" : "female" } }])}
            var testQuery = query.Where(containsTagFemale);
            queryResult = testQuery.ToList <MongoItem>();
            Debug.Assert(queryResult.Count() == 5);
            queryResult = query4.ToList <MongoItem>();
            queryResult.Assert(new string[] { "Nina Huber", "Michaela Bauer" });
            queryResult = query5.ToList <MongoItem>();
            queryResult.Assert(new string[] { "Martina Uhlig" });
        }
Exemplo n.º 30
0
 public Task AggregateToCollectionAsync <TResult>(IClientSessionHandle session, PipelineDefinition <SitePage, TResult> pipeline, AggregateOptions options = null, CancellationToken cancellationToken = default)
 {
     throw new NotImplementedException();
 }