コード例 #1
0
ファイル: NodesController.cs プロジェクト: xlgwr/osdr
        private async Task <IEnumerable <BaseNode> > GetBreadcrumbs(BsonDocument node)
        {
            var filter  = (BsonDocument) new OrganizeFilter(UserId.Value).ById(node["_id"].AsGuid);
            var parents = await _nodes.Aggregate().Match(filter)
                          .GraphLookup(_nodes, "ParentId", "_id", "$ParentId", "Parent")
                          .Unwind("Parent")
                          .ReplaceRoot <BaseNode>("$Parent")
                          .ToListAsync();

            parents.AsParallel()
            .ForAll(p => p.Name = WebUtility.UrlEncode(p.Name)?.Replace("+", "%20"));

            if (parents.Count() > 0)
            {
                var result = new List <BaseNode>();
                var it     = parents.First(p => p.Id == node["ParentId"].AsGuid);
                result.Add(it);
                while (it.Id != UserId)
                {
                    it = parents.First(p => p.Id == it.ParentId);
                    result.Add(it);
                }

                return(result);
            }
            else
            {
                return(parents);
            }
        }
コード例 #2
0
        public async Task <IEnumerable <AppraisalForApprovalDto> > GetEmployeesToAppraise(int employeeId, string appraisalConfigurationId, string appraisalCycleId, string whoAmI)
        {
            var year         = DateTime.Now.Year;
            var pipeline     = SupervisorEmployeeQuery.GetEmployeesToAppraise(employeeId, appraisalConfigurationId, appraisalCycleId);
            var lookupResult = KraCollection.Aggregate <AppraisalForApprovalDto>(pipeline);

            var finalResultToReturn = await GenerateDistinctArrayForEmployeeKRA(lookupResult);

            if (finalResultToReturn.Count > 0)
            {
                //get Equivalent Employee Details for each one
                IEnumerable <string> IdsToSend = finalResultToReturn.Select(x => x.EmployeeDetail.EmployeeId.ToString()).Distinct();
                var returnedEmployees          = await teamRepository.FetchEmployeesDetailsFromEmployeeService(IdsToSend);

                if (returnedEmployees.Any())
                {
                    foreach (var employee in returnedEmployees)
                    {
                        var currentEmployee = finalResultToReturn.FirstOrDefault(x => x.EmployeeDetail.EmployeeId == employee.EmployeeId);
                        currentEmployee.EmployeeDetail.Email      = employee.Email;
                        currentEmployee.EmployeeDetail.EmpStaffId = employee.StaffId;
                        currentEmployee.EmployeeDetail.FullName   = employee.FullName;
                        currentEmployee.EmployeeDetail.Company    = employee.Subgroup.Name;
                    }
                }
            }
            return(finalResultToReturn);
        }
コード例 #3
0
        /// <summary>
        ///     Get a <see cref="Movie" />
        /// </summary>
        /// <param name="movieId">The Id of the <see cref="Movie" /></param>
        /// <param name="cancellationToken">Allows the UI to cancel an asynchronous request. Optional.</param>
        /// <returns>The <see cref="Movie" /></returns>
        public async Task <Movie> GetMovieAsync(string movieId, CancellationToken cancellationToken = default)
        {
            try
            {
                return(await _moviesCollection.Aggregate()
                       .Match(Builders <Movie> .Filter.Eq(x => x.Id, movieId))
                       .Lookup(
                           _commentsCollection,
                           m => m.Id,
                           c => c.MovieId,
                           (Movie m) => m.Comments
                           )
                       .FirstOrDefaultAsync(cancellationToken));
            }

            catch (Exception ex)
            {
                // TODO Ticket: Error Handling
                // Catch the exception and check the exception type and message contents.
                // Return null if the exception is due to a bad/missing Id. Otherwise,
                // throw.

                return(null);
            }
        }
コード例 #4
0
        public List <TopTenMatch> GetTopTenMatches(MatchDuration duration)
        {
            var filter = Builders <Player> .Filter
                         .Where(x => x.matches.All(m => m.date >= duration.FromDate & m.date <= duration.ToDate));

            var filterBson = Builders <BsonDocument> .Filter
                             .Where(x => x["matches"]["date"] >= duration.FromDate& x["matches"]["date"] <= duration.ToDate);

            var documents = playerList
                            .Aggregate()
                            .Unwind(x => x.matches)
                            .Match(filterBson)
                            .SortByDescending(x => x["matches"]["score"])
                            .Limit(10)
                            .ToList();

            List <TopTenMatch> topTenMatches = new List <TopTenMatch>();

            foreach (var item in documents)
            {
                TopTenMatch match = new TopTenMatch();
                match.score           = item["matches"]["score"].ToDouble();
                match.level_number    = item["matches"]["level_number"].ToInt32();
                match.date            = item["matches"]["date"].ToUniversalTime();
                match.player_nickname = item["nickname"].ToString();
                topTenMatches.Add(match);
            }
            return(topTenMatches);
        }
コード例 #5
0
        public IEnumerable <BaseNode> GetBreadcrumbs(Guid itemId)
        {
            var filter = _filterBase & _builder.Eq("_id", itemId);

            var parents = _nodes.Aggregate().Match(filter)
                          .GraphLookup(_nodes, "ParentId", "_id", "$ParentId", "Parent")
                          .Unwind("Parent")
                          .ReplaceRoot <BaseNode>("$Parent")
                          .ToList();

            if (parents.Count() > 0)
            {
                var result = new List <BaseNode>();
                var it     = parents.First(p => p.Type == "User");
                do
                {
                    result.Add(it);
                    it = parents.FirstOrDefault(p => p.ParentId == it.Id);
                } while (it != null);

                return(result);
            }
            else
            {
                return(parents);
            }
        }
コード例 #6
0
        /// <summary>
        ///     Get a <see cref="Movie" />
        /// </summary>
        /// <param name="movieId">The Id of the <see cref="Movie" /></param>
        /// <param name="cancellationToken">Allows the UI to cancel an asynchronous request. Optional.</param>
        /// <returns>The <see cref="Movie" /></returns>
        public async Task <Movie> GetMovieAsync(string movieId, CancellationToken cancellationToken = default)
        {
            var rx = new Regex(@"^[0-9A-F]+$");

            if (string.IsNullOrWhiteSpace(movieId) || movieId.Length != 24 || !rx.IsMatch(movieId))
            {
                return(null);
            }
            try
            {
                return(await _moviesCollection.Aggregate()
                       .Match(Builders <Movie> .Filter.Eq(x => x.Id, movieId))
                       .Lookup(_commentsCollection,
                               m => m.Id,
                               c => c.MovieId,
                               (Movie m) => m.Comments).FirstOrDefaultAsync(cancellationToken));

                // Ticket: Get Comments
                // Add a lookup stage that includes the
                // comments associated with the retrieved movie
            }

            catch (Exception ex)
            {
                // TODO Ticket: Error Handling
                // Catch the exception and check the exception type and message contents.
                // Return null if the exception is due to a bad/missing Id. Otherwise,
                // throw.

                throw;
            }
        }
コード例 #7
0
        private async Task <IList <Event> > GetEventsForChat(Chat chat, EntityID since, int limit)
        {
            var graphLookupStage = new BsonDocument("$graphLookup",
                                                    new BsonDocument
            {
                { "from", EventsCollectionName },
                { "startWith", "{ EventID: " + since + " }" },
                { "connectFromField", "EventID" },
                { "connectToField", "PrevEvents" },
                { "as", "Children" },
                { "maxDepth", limit },
                { "restrictSearchWithMatch", "{ ChatId: " + chat.Id + " }" }
            });

            var result = await events.Aggregate()
                         .AppendStage <BsonDocument>(graphLookupStage).ToListAsync();

            var deserializedResult = new List <Event>();

            result.ForEach(x =>
            {
                deserializedResult.Add(BsonSerializer.Deserialize <EventWithChildren>(x));
            });

            return(deserializedResult);
        }
コード例 #8
0
        private OverviewDetails LoadCashOverview()
        {
            OverviewDetails details = new OverviewDetails();
            IAggregateFluent <HandHistory> cashGameHands =
                handCollection.Aggregate().Match(h => h.GameDescription.PokerFormat == PokerFormat.CashGame &&
                                                 h.GameDescription.Limit.Currency != Currency.PlayMoney);

            IAggregateFluent <UnwoundHand> actions = cashGameHands
                                                     .Unwind <HandHistory, UnwoundHand>(h => h.HandActions)
                                                     .Match(h => PlayerNames.Contains(h.HandActions.PlayerName));

            if (!cashGameHands.Any())
            {
                return(details);     // Return empty result set if there are no hands available
            }
            details.Hands = cashGameHands.Count().First().Count;

            foreach (var profit in actions.Group(h => h.HandId, h => new { sum = h.Sum(h2 => h2.HandActions.Amount * h2.GameDescription.Limit.BigBlind) }).ToEnumerable())
            {
                if (profit.sum > 0)
                {
                    details.Winnings += profit.sum;
                }
                else
                {
                    details.Losses += profit.sum;
                }
            }

            return(details);
        }
コード例 #9
0
        /// <summary>
        /// Get a <see cref="Movie"/>
        /// </summary>
        /// <param name="movieId">The Id of the <see cref="Movie"/></param>
        /// <param name="cancellationToken">Allows the UI to cancel an asynchronous request. Optional.</param>
        /// <returns>The <see cref="Movie"/></returns>
        public async Task <Movie> GetMovieAsync(string movieId, CancellationToken cancellationToken = default)
        {
            if (string.IsNullOrEmpty(movieId))
            {
                return(null);
            }

            try
            {
                return(await _moviesCollection.Aggregate()
                       .Match(Builders <Movie> .Filter.Eq(x => x.Id, movieId))
                       .Lookup(
                           _commentsCollection,
                           m => m.Id,
                           c => c.MovieId,
                           (Movie m) => m.Comments
                           )
                       .FirstOrDefaultAsync(cancellationToken));
            }
            catch (FormatException ex)
            {
                if (ex.Message.Contains("is not a valid 24 digit hex string"))
                {
                    return(null);
                }

                throw;
            }
        }
コード例 #10
0
        public User GetSortedUserBlogs(string userId)
        {
            var res = users.Aggregate <User>()
                      .Match(new BsonDocument {
                { "_id", userId }
            })
                      .Unwind(u => u.Blogs)
                      .Sort(new BsonDocument {
                { $"{nameof(User.Blogs)}.{nameof(Blog.CreatedOn)}", -1 }
            })
                      .Group(new BsonDocument {
                { "_id", "$_id" },
                { $"{nameof(User.Blogs)}", new BsonDocument {
                      { "$push", $"${nameof(User.Blogs)}" }
                  } }
            }).ToList();

            if (res.Count == 0)
            {
                throw new UserNotFoundException();
            }

            var user = BsonSerializer.Deserialize <User>(res.First());

            return(user);
        }
コード例 #11
0
        /// <summary>
        ///     Get a <see cref="Movie" />
        /// </summary>
        /// <param name="movieId">The Id of the <see cref="Movie" /></param>
        /// <param name="cancellationToken">Allows the UI to cancel an asynchronous request. Optional.</param>
        /// <returns>The <see cref="Movie" /></returns>
        public async Task <Movie> GetMovieAsync(string movieId, CancellationToken cancellationToken = default)
        {
            try
            {
                // Add a lookup stage that includes the
                // comments associated with the retrieved movie
                var filter = Builders <Movie> .Filter.Eq(x => x.Id, movieId);

                var movieWithComments = await _moviesCollection.Aggregate()
                                        .Match(filter)
                                        .Lookup
                                        (
                    _commentsCollection,
                    m => m.Id,
                    c => c.MovieId,
                    (Movie m) => m.Comments
                                        )
                                        .FirstOrDefaultAsync(cancellationToken);

                return(movieWithComments);
            }

            catch (Exception ex)
            {
                // Catch the exception and check the exception type and message contents.
                // Return null if the exception is due to a bad/missing Id. Otherwise,
                // throw.
                if (ex.Message.Contains("not a valid"))
                {
                    return(null);
                }
                throw;
            }
        }
コード例 #12
0
        /// <summary>
        /// Creates an aggregation pipeline that finds all documents that have a string
        /// 'lastupdated' value and converts those values to type 'date'.
        ///
        /// The code below is the C# way to represent the following pipeline:
        ///
        /// [{'$match': {'lastupdated': {'$type': 2}}}, { '$addFields': {'lastupdated':
        /// {'$dateFromString': { 'dateString': {'$substr': ['$lastupdated', 0, 23]}}}}}] ///
        /// </summary>
        /// <returns>A List of Movie objects with the lastupdated values converted to dates.</returns>
        private static List <Movie> TransformDatePipeline()
        {
            var pipeline = new[]
            {
                new BsonDocument("$match",
                                 new BsonDocument("lastupdated",
                                                  new BsonDocument("$type", 2))),
                new BsonDocument("$addFields",
                                 new BsonDocument("lastupdated",
                                                  new BsonDocument("$dateFromString",
                                                                   new BsonDocument
                {
                    {
                        "dateString",
                        new BsonDocument("$substr",
                                         new BsonArray
                        {
                            "$lastupdated",
                            0,
                            23
                        })
                    },
                    { "timezone", "America/New_York" }
                })))
            };

            return(_moviesCollection
                   .Aggregate(PipelineDefinition <Movie, Movie> .Create(pipeline))
                   .ToList());
        }
コード例 #13
0
ファイル: Datablase.cs プロジェクト: xSke/BlaseballData
        public async Task UpdateGameIndex()
        {
            Log.Information("Reindexing game collection");
            await _gameUpdates.Aggregate(new AggregateOptions { AllowDiskUse = true })
            .Sort("{firstSeen: 1}")
            .Group(@"{
                    _id: '$game',
                    season: {$first: '$payload.season'},
                    day: {$first: '$payload.day'},
                    lastUpdate: {$last: '$payload'},
                    lastUpdateTime: {$last: '$firstSeen'}
                }")
            .MergeAsync(_games);

            Log.Information("Reindexing game start timestamps");
            await _gameUpdates.Aggregate(new AggregateOptions { AllowDiskUse = true })
            .Match("{'payload.gameStart': true}")
            .Group(@"{
                    _id: '$game',
                    start: {$min: '$firstSeen'},
                }")
            .MergeAsync(_games);

            Log.Information("Reindexing game end timestamps");
            await _gameUpdates.Aggregate(new AggregateOptions { AllowDiskUse = true })
            .Match("{'payload.gameComplete': true}")
            .Group(@"{
                    _id: '$game',
                    end: {$min: '$firstSeen'},
                }")
            .MergeAsync(_games);

            Log.Information("Done! :)");
        }
コード例 #14
0
        /// <summary>
        ///     Get a <see cref="Movie" />
        /// </summary>
        /// <param name="movieId">The Id of the <see cref="Movie" /></param>
        /// <param name="cancellationToken">Allows the UI to cancel an asynchronous request. Optional.</param>
        /// <returns>The <see cref="Movie" /></returns>
        public async Task <Movie> GetMovieAsync(string movieId, CancellationToken cancellationToken = default)
        {
            try
            {
                return(await _moviesCollection.Aggregate()
                       .Match(Builders <Movie> .Filter.Eq(x => x.Id, movieId))
                       // Ticket: Get Comments
                       // Add a lookup stage that includes the
                       // comments associated with the retrieved movie
                       .Lookup(
                           _commentsCollection,
                           m => m.Id,
                           c => c.MovieId,
                           (Movie m) => m.Comments
                           )
                       .FirstOrDefaultAsync(cancellationToken));
            }

            catch (Exception ex)
            {
                // TODO Ticket: Error Handling
                // Catch the exception and check the exception type and message contents.
                // Return null if the exception is due to a bad/missing Id. Otherwise,
                // throw.

                if (ex.Message.ToLower().EndsWith("is not a valid 24 digit hex string."))
                {
                    return(null);
                }

                throw;
            }
        }
コード例 #15
0
ファイル: MoviesRepository.cs プロジェクト: joao2391/M220N
        /// <summary>
        ///     Get a <see cref="Movie" />
        /// </summary>
        /// <param name="movieId">The Id of the <see cref="Movie" /></param>
        /// <param name="cancellationToken">Allows the UI to cancel an asynchronous request. Optional.</param>
        /// <returns>The <see cref="Movie" /></returns>
        public async Task <Movie> GetMovieAsync(string movieId, CancellationToken cancellationToken = default)
        {
            try
            {
                return(await _moviesCollection.Aggregate()
                       .Match(Builders <Movie> .Filter.Eq(x => x.Id, movieId))
                       .Lookup <Movie, Comment, Movie>(_commentsCollection,
                                                       m => m.Id, c => c.MovieId, r => r.Comments)
                       .FirstOrDefaultAsync());

                //await _moviesCollection.Aggregate()
                //.Match(Builders<Movie>.Filter.Eq(x => x.Id, movieId))
                //.Lookup("comments", movieId, movieId, "movie_comments");
                //.Lookup("comments", movieId, movieId, "movie_comments")
                // Ticket: Get Comments
                // Add a lookup stage that includes the
                // comments associated with the retrieved movie
                //.FirstOrDefaultAsync(cancellationToken);
            }

            catch (Exception ex)
            {
                // TODO Ticket: Error Handling
                // Catch the exception and check the exception type and message contents.
                // Return null if the exception is due to a bad/missing Id. Otherwise,
                // throw.
                return(null);
            }
        }
コード例 #16
0
        public void LoadOverview()
        {
            OverviewDetails cashGameDetails = LoadCashOverview();

            AddStatistic("cashHands", cashGameDetails.Hands.ToString());
            AddStatistic("cashWinnings", cashGameDetails.Winnings.ToString(dollarPattern));
            AddStatistic("cashLosses", cashGameDetails.Losses.ToString(dollarPattern));

            OverviewDetails tournamentDetails = LoadTournamentOverview(false);

            AddStatistic("tournamentHands", tournamentDetails.Hands.ToString());
            AddStatistic("tournamentWinnings", tournamentDetails.Winnings.ToString(dollarPattern));
            AddStatistic("freerollWinnings", () =>
                         tournamentCollection.Aggregate().Match(t => t.Buyin.Total == 0)
                         .Group(t => t.SitAndGo, t => new { sum = t.Sum(t2 => t2.Winnings) }).First().sum.ToString(dollarPattern));
            AddStatistic("tournamentCosts", tournamentDetails.Losses.ToString(dollarPattern));
            AddStatistic("tournamentsPlayed", tournamentDetails.Tournaments.ToString());

            OverviewDetails sitAndGoDetails = LoadTournamentOverview(true);

            AddStatistic("sitAndGoHands", sitAndGoDetails.Hands.ToString());
            AddStatistic("sitAndGoWinnings", sitAndGoDetails.Winnings.ToString(dollarPattern));
            AddStatistic("sitAndGoCosts", sitAndGoDetails.Losses.ToString(dollarPattern));
            AddStatistic("sitAndGosPlayed", sitAndGoDetails.Tournaments.ToString());


            decimal totalProfit =
                cashGameDetails.Winnings + tournamentDetails.Winnings + sitAndGoDetails.Winnings +
                cashGameDetails.Losses + tournamentDetails.Losses + sitAndGoDetails.Losses;
            long totalHands = cashGameDetails.Hands + tournamentDetails.Hands + sitAndGoDetails.Hands;

            AddStatistic("handsPlayed", totalHands.ToString());
            AddStatistic("profit", totalProfit.ToString(dollarPattern));
        }
コード例 #17
0
ファイル: UsuarioService.cs プロジェクト: jossh4321/SYSGED
        public async Task <List <UsuarioRDTO> > obtenerFiscales()
        {
            BsonArray subpipeline = new BsonArray();

            subpipeline.Add(
                new BsonDocument("$match", new BsonDocument(
                                     "$expr", new BsonDocument(
                                         "$eq", new BsonArray {
                "$_id", new BsonDocument("$toObjectId", "$$idrol")
            }
                                         )
                                     ))
                );
            var lookup = new BsonDocument("$lookup",
                                          new BsonDocument("from", "roles")
                                          .Add("let", new BsonDocument("idrol", "$rol"))
                                          .Add("pipeline", subpipeline)
                                          .Add("as", "rolobj"));

            var filter2 = new BsonDocument("$match",
                                           new BsonDocument("rolobj.label", "Fiscal"));
            var filter1 = new BsonDocument("$match",
                                           new BsonDocument("tipo", "administracion"));

            List <UsuarioRDTO> fiscales = new List <UsuarioRDTO>();

            fiscales = await _usuarios.Aggregate()
                       .AppendStage <Usuario>(filter1)
                       .AppendStage <Usuario_LK>(lookup)
                       .Unwind <Usuario_LK, UsuarioRDTO>(p => p.rolobj)
                       .AppendStage <UsuarioRDTO>(filter2)
                       .ToListAsync();

            return(fiscales);
        }
コード例 #18
0
        /// <summary>
        /// Gets view statistics for all presentations that have been viewed at least once.
        /// </summary>
        /// <returns>A list of objects containing presentation view statistics.</returns>
        public async Task <IEnumerable <StatisticsPresentationModel> > GetStatisticsPresentationListAsync()
        {
            var aggregate = statisticsCollection
                            .Aggregate()
                            .Match(new BsonDocument {
                { "Type", "presentation" },
            })
                            .Group(new BsonDocument {
                { "_id", "$PresentationId" },
                { "TimesShown", new BsonDocument("$sum", 1) },
                { "LastShown", new BsonDocument("$last", "$Time") }
            })
                            .Sort(Builders <BsonDocument> .Sort.Descending("TimesShown").Descending("LastShown"))
                            .Project(new BsonDocument
            {
                { "_id", 0 },
                { "PresentationId", "$_id" },
                { "TimesShown", "$TimesShown" },
                { "LastShown", "$LastShown" }
            });

            var results = await aggregate.ToListAsync();

            var statisticsPresentationList = new List <StatisticsPresentationModel>();

            foreach (var item in results)
            {
                statisticsPresentationList.Add(BsonSerializer.Deserialize <StatisticsPresentationModel>(item));
            }

            return(statisticsPresentationList);
        }
コード例 #19
0
        /// <summary>
        ///     Get a <see cref="Movie" /> with <see cref="Comment" /> collection
        /// </summary>
        public async Task <Movie> GetMovieAsync(string movieId, CancellationToken cancellationToken = default)
        {
            try
            {
                var movie = await _moviesCollection.Aggregate()
                            .Match(Builders <Movie> .Filter.Eq(x => x.Id, movieId))
                            // Add a lookup (left join) stage that includes the comments associated with the retrieved movie
                            .Lookup(_commentsCollection,
                                    m => m.Id,
                                    (Comment c) => c.MovieId,
                                    (Movie m) => m.Comments)
                            .FirstOrDefaultAsync(cancellationToken);

                return(movie);
            }
            catch (Exception ex)
            {
                // Catch the exception and check the exception type and message contents.
                // Return null if the exception is due to a bad/missing Id. Otherwise, throw.
                if (ex.GetType() == typeof(FormatException) && ex.Message.Contains("is not a valid 24 digit hex string"))
                {
                    return(null);
                }

                throw;
            }
        }
コード例 #20
0
        public IDataAdapter Aggregate(object pipeline, out string result)
        {
            AggregatePipelineModel model   = (AggregatePipelineModel)pipeline;
            BsonDocument           Match   = BsonDocument.Parse(model.Match);
            BsonDocument           Sort    = BsonDocument.Parse(model.Sort);
            BsonDocument           Group   = BsonDocument.Parse(model.Group);
            BsonDocument           Project = BsonDocument.Parse(model.Project);

            if (model.Lookup == null)
            {
                result = _collection.Aggregate()
                         .Match(Match)
                         .Group(Group)
                         .Project(Project)
                         .Sort(Sort)
                         .ToList().ToJson();
            }
            else
            {
                result = _collection.Aggregate()
                         .Match(Match)
                         .Group(Group)
                         .Project(Project)
                         .Lookup(model.Lookup.ForeignCollectionName,
                                 model.Lookup.LocalFieldName,
                                 model.Lookup.ForeignFieldName,
                                 model.Lookup.ResultAs)
                         .Sort(Sort)
                         .ToList().ToJson();
            }

            return(this);
        }
コード例 #21
0
ファイル: DataAccess.cs プロジェクト: wyshp/idionline
        //public string GenerateIdiom()
        //{
        //    Dictionary<string, string> dic = new Dictionary<string, string>
        //    {
        //        { "5beghawgsagsaga7eb855e3e94", "66hhh" },
        //        { "5bebec2a2hgbhghhhhhhhh855e3e94", "6gggggh" }
        //    };
        //    Definition def = new Definition { Text = "hahaha", Addition = "666", IsBold = false, Source = "hhh", Links = dic };
        //    Definition def2 = new Definition { Text = "haa", Addition = "345sgsdgsdgc6", IsBold = false, Source = "hhh", Links = dic };
        //    List<Definition> defs = new List<Definition>
        //    {
        //        def,
        //        def2
        //    };
        //    _idioms.InsertOne(new Idiom { Name = "TEST", Definitions = defs, LastEditor = "fssssss", UpdateTimeUT = 666666, Index = 'C' });
        //    return "Done!";
        //}

        //public string GenerateLaunchInf()
        //{
        //    Dictionary<string, string> i = new Dictionary<string, string> {                { "aaaaaaaa", "6ggggh" },
        //        { "5bshedfhdfh4", "6gadfadah" }};
        //    _launchInf.InsertOne(new LaunchInf { Text = "23333", DailyIdiom = null, /*DailyIdiomName = "6666",*/  ThemeColor = null, LogoUrl = null, DisableAds = false, /*FloatEasterEggs = i, */DateUT = DateTimeOffset.MinValue.ToUnixTimeSeconds() });
        //    return "Done!";
        //}
        #endregion
        //这里生成每日成语。
        public void GenLI()
        {
            DateTimeOffset dateUT = DateTimeOffset.Now;
            int            hour   = dateUT.Hour;
            int            min    = dateUT.Minute;
            int            sec    = dateUT.Second;
            long           dateL  = dateUT.AddSeconds(-sec).AddMinutes(-min).AddHours(-hour).ToUnixTimeSeconds();
            //默认的每日成语。
            Idiom     deftIdiom = _launchInf.Find(x => x.DateUT == DateTimeOffset.MinValue.ToUnixTimeSeconds()).FirstOrDefault().DailyIdiom;
            LaunchInf inf       = _launchInf.Find(x => x.DateUT == dateL).FirstOrDefault();
            //从数据库里随机抽取一条成语。
            Idiom idi = _idioms.Aggregate().AppendStage <Idiom>("{$sample:{size:1}}").FirstOrDefault();

            //当idi不为null才运行。
            if (idi != null)
            {
                if (inf == null)
                {
                    //这种情况说明当天的inf还没有生成。
                    if (deftIdiom == null)
                    {
                        //若默认成语为空,则生成每日成语。
                        LaunchInf ins = new LaunchInf {
                            Version = null, ArgsDic = null, Text = null, ThemeColor = null, LogoUrl = null, DisableAds = false, DailyIdiom = idi, IdiomsCount = 0, DateUT = dateL
                        };
                        _launchInf.InsertOne(ins);
                    }
                    else
                    {
                        //不为空则将默认成语写入当天的启动信息,方便以后查询记录。
                        LaunchInf ins = new LaunchInf {
                            Version = null, ArgsDic = null, Text = null, ThemeColor = null, LogoUrl = null, DisableAds = false, DailyIdiom = deftIdiom, IdiomsCount = 0, DateUT = dateL
                        };
                        _launchInf.InsertOne(ins);
                    }
                }
                else
                {
                    //这种情况说明当天的inf已经提前编辑好了,根据需要补全。
                    if (inf.DailyIdiom == null)
                    {
                        if (deftIdiom == null)
                        {
                            //若默认成语为空,则生成每日成语。
                            UpdateDefinition <LaunchInf> upd = Builders <LaunchInf> .Update.Set("DailyIdiom", idi);

                            _launchInf.UpdateOne(x => x.DateUT == dateL, upd);
                        }
                        else
                        {
                            //不为空则将默认成语写入当天的启动信息,方便以后查询记录。
                            UpdateDefinition <LaunchInf> upd = Builders <LaunchInf> .Update.Set("DailyIdiom", deftIdiom);

                            _launchInf.UpdateOne(x => x.DateUT == dateL, upd);
                        }
                    }
                }
            }
        }
コード例 #22
0
 public IAsyncCursor <TResult> Aggregate <TResult>(
     PipelineDefinition <T, TResult> pipeline,
     AggregateOptions?options            = null,
     CancellationToken cancellationToken = default
     )
 {
     return(collection.Aggregate(pipeline, options, cancellationToken));
 }
コード例 #23
0
 public IDictionary <double, int> GetDistributionByEnergyValue()
 {
     return(_collection.Aggregate()
            .Group(new BsonDocument {
         { "_id", "$EstimatedValue" }, { "count", new BsonDocument("$sum", 1) }
     }).ToList()
            .ToDictionary(d => d["_id"].AsDouble, d => d["count"].AsInt32));
 }
コード例 #24
0
ファイル: RoleService.cs プロジェクト: RafidiaAR/Consap
        public List <BsonDocument> GetAll()
        {
            var data = _Role.Aggregate()
                       .Lookup("Permission", "PermissionId", "_id", "Permission")
                       .ToList();

            return(data);
        }
コード例 #25
0
        public async Task <UsuarioDTO_UnwindRol> ObtenerUsuarioRol(string id)
        {
            var match = new BsonDocument("$match",
                                         new BsonDocument("_id", new ObjectId(id)));

            //lookup para roles
            var subpipeline_rol = new BsonArray
            {
                new BsonDocument("$match",
                                 new BsonDocument("$expr",
                                                  new BsonDocument("$eq",
                                                                   new BsonArray
                {
                    "$_id",
                    new BsonDocument("$toObjectId", "$$idrol")
                })))
            };

            var lookup_rol = new BsonDocument("$lookup",
                                              new BsonDocument
            {
                { "from", "roles" },
                { "let",
                  new BsonDocument("idrol", "$rol") },
                { "pipeline", subpipeline_rol },
                { "as", "rolobj" }
            });
            //lookup para permisos
            var subpipeline_permiso = new BsonArray
            {
                new BsonDocument("$match",
                                 new BsonDocument("$expr",
                                                  new BsonDocument("$eq",
                                                                   new BsonArray
                {
                    "$_id",
                    new BsonDocument("$toObjectId", "$$idpermiso")
                })))
            };
            var lookup_permiso = new BsonDocument("$lookup",
                                                  new BsonDocument
            {
                { "from", "permisos" },
                { "let",
                  new BsonDocument("idpermiso", "$rolobj.permisos") },
                { "pipeline", subpipeline_permiso },
                { "as", "permisos" }
            });

            UsuarioDTO_UnwindRol usuario = new UsuarioDTO_UnwindRol();

            usuario = await _usuarios.Aggregate()
                      .AppendStage <Usuario>(match)
                      .AppendStage <UsuarioDTO>(lookup_rol)
                      .Unwind <UsuarioDTO, UsuarioDTO_UnwindRol>(x => x.rolobj).SingleOrDefaultAsync();

            return(usuario);
        }
コード例 #26
0
ファイル: Lookups.cs プロジェクト: TsypchenkoYuliia/MongoTest
        public void GetMovieWithCommentCount1()
        {
            var filter = new BsonDocument[]
            {
                new BsonDocument("$match",
                                 new BsonDocument("year",
                                                  new BsonDocument
                {
                    { "$gte", 1980 },
                    { "$lt", 1990 }
                })),
                new BsonDocument("$lookup",
                                 new BsonDocument
                {
                    { "from", "comments" },
                    { "let", new BsonDocument("id", "$_id") },
                    { "pipeline",
                      new BsonArray
                      {
                          new BsonDocument("$match",
                                           new BsonDocument("$expr",
                                                            new BsonDocument("$eq",
                                                                             new BsonArray
                            {
                                "$movie_id",
                                "$$id"
                            }))),
                          new BsonDocument("$count", "count")
                      } },
                    { "as", "movie_comments" }
                })
            };

            /* We can then define that as a PipelineDefinition object,
             * which we pass to the Aggregate() function on the Movies
             * collection:
             */

            var pipeline = PipelineDefinition <Movie, BsonDocument>
                           .Create(filter);

            var movies = _moviesCollection.Aggregate(pipeline).ToList();

            var firstMovie = movies.First();

            Assert.AreEqual(2081, movies.Count);
            var comments = (BsonDocument)firstMovie.GetValue("movie_comments")[0];
            var count    = (int)comments.GetValue("count");

            Assert.AreEqual(1, count);

            /* And we can see that it works. But this code isn't exactly
             * easy to debug or change, should we need to. As
             * we've already discussed in this course, there are multiple ways
             * to accomplish tasks with the driver, so let's look at an
             * approach that makes more sense and is easy to decipher:
             */
        }
コード例 #27
0
        /// <inheritdoc />
        public IEnumerable <VoucherDetail> SelectVoucherDetails(IVoucherDetailQuery query)
        {
            var preF = query.VoucherQuery.Accept(new MongoDbNativeVoucher());
            var chk  = GetChk(query);
            var srt  = Builders <Voucher> .Sort.Ascending("date");

            return(m_Vouchers.Aggregate().Match(preF).Sort(srt).Project(ProjectDetails).Unwind("detail").Match(chk)
                   .Project(ProjectDetail).ToEnumerable().Select(b => BsonSerializer.Deserialize <VoucherDetail>(b)));
        }
コード例 #28
0
        public IAggregateFluent <TDocument> Aggregate(IOspSession session)
        {
            ArgumentValidation.Validate(nameof(session), session);

            return(_documentCollection.Aggregate(((IOspSessionInternal)session).SessionHandle,
                                                 new AggregateOptions {
                AllowDiskUse = true
            }));
        }
コード例 #29
0
        public void Aggregate()
        {
            var users = _users.Aggregate().Project(u => new { u.RegistartionId })
                        .Group(u => u.RegistartionId, u => new { u.Key, Count = u.Count() }).Limit(4).ToList();

            var users1 = _users.Aggregate().Match(u => u.Phones != null).Project(u => new { u.Id, c = u.Phones.Count() }).ToList();

            users.ForEach(u => _helper.WriteLine($"RegistartionId {u.Key} Count {u.Count}"));
            users1.ForEach(u => _helper.WriteLine($"{u.c}"));
        }
コード例 #30
0
        public double GetAverageEnergy()
        {
            var bsonElements = _bsonCollection.Aggregate().Group(new BsonDocument {
                { "_id", "$EstimatedValue" }
            }).ToList();

            var values = bsonElements.Select(bsonDoc => bsonDoc[0].AsDouble).ToList();

            return(values.Average());
        }
コード例 #31
0
        private async Task GetFutureTweets(string user, IMongoCollection<BsonDocument> tweets)
        {
            int tweetsCount = 0, tweetsProcessed = 0, tweetsMax = MaxTweets;
            var filter = GetFilter(user);
            var aggdef = tweets.Aggregate()
                .Match(filter)
                .Group(new BsonDocument { { "_id", "$user.screen_name" }, { "max", new BsonDocument("$max", "$id") } });
            var aggresult = await aggdef.FirstOrDefaultAsync();
            var maxid = aggresult["max"].AsNullableInt64;

          


            do
            {
                var query = string.Format(api_path, user);

                if (maxid.HasValue)
                {
                    query = query + "&since_id={0}";
                    query = string.Format(query, maxid + 1);
                }

                var jsonObject = TwitterDownloader.ExecuteJsonGETQuery(query);
                List<object> otweets = (List<object>)JsonConvert.DeserializeObject<List<object>>(jsonObject);
                tweetsCount = otweets.Count;
                tweetsProcessed += tweetsCount;
                _log.Info("Getting {0} new tweets for user:{1}", otweets.Count, user);

                foreach (object oTweet in otweets)
                {
                    var bson = BsonDocument.Parse(oTweet.ToString());
                    tweets.InsertOneAsync(bson).Wait();
                    long? nmax = bson["id"].AsNullableInt64;
                    if (nmax > maxid)
                        maxid = nmax;
                }
            }
            while (tweetsCount > 0 && tweetsProcessed < tweetsMax);
        }