Пример #1
0
        public async Task <List <Movie> > GetMovies(int yearLowerBand, int yearUpperBand)
        {
            var movies = new List <Movie>();

            var projectionBuilder = new ProjectionDefinitionBuilder <Movie>();
            var projection        = projectionBuilder
                                    .Include(x => x.Awards)
                                    .Include(x => x.Genres)
                                    .Include(x => x.Plot)
                                    .Include(x => x.Rated)
                                    .Include(x => x.Title)
                                    .Include(x => x.Year)
                                    .Exclude("_id");

            var filterBuilder = new FilterDefinitionBuilder <Movie>();
            var filter        = filterBuilder.Gte(x => x.Year, yearLowerBand) & filterBuilder.Lte(x => x.Year, yearUpperBand);

            using (IAsyncCursor <Movie> documents = await _database.GetCollection <Movie>("movies")
                                                    .FindAsync(filter, new FindOptions <Movie, Movie>
            {
                Projection = projection
            }))
            {
                while (documents.MoveNext())
                {
                    movies.AddRange(documents.Current);
                }
            }

            return(movies);
        }
Пример #2
0
        public async Task <dynamic> GetById(string userId, string songId)
        {
            var userCollection = MongoWrapper.Database.GetCollection <Models.Musician>(nameof(Models.User));

            var songFilterBuilder = new FilterDefinitionBuilder <Models.Song>();
            var songFilter        = songFilterBuilder.And
                                    (
                songFilterBuilder.Eq(s => s._id, new ObjectId(songId)),
                GeneralUtils.NotDeactivated(songFilterBuilder)
                                    );

            var userFilterBuilder = new FilterDefinitionBuilder <Models.Musician>();
            var userFilter        = userFilterBuilder.And
                                    (
                userFilterBuilder.Eq(u => u._id, new ObjectId(userId)),
                GeneralUtils.NotDeactivated(userFilterBuilder)
                                    );

            var userProjectionBuilder = new ProjectionDefinitionBuilder <Models.Musician>();
            var userProjection        = userProjectionBuilder
                                        .ElemMatch(m => m.Songs, songFilter);

            var user = (await userCollection.FindAsync(userFilter, new FindOptions <Models.Musician>
            {
                Limit = 1,
                Projection = userProjection,
            })).SingleOrDefault();

            if (user == null)
            {
                Response.StatusCode = (int)HttpStatusCode.NotFound;
                return(new ResponseBody
                {
                    Code = ResponseCode.NotFound,
                    Success = false,
                    Message = "Usuário não encontrado!",
                });
            }

            var song = user.Songs?.SingleOrDefault();

            if (song == default)
            {
                Response.StatusCode = (int)HttpStatusCode.NotFound;
                return(new ResponseBody
                {
                    Code = ResponseCode.NotFound,
                    Success = false,
                    Message = "Música não encontrada!",
                });
            }

            return(new ResponseBody
            {
                Code = ResponseCode.GenericSuccess,
                Success = true,
                Message = "Música encontrada com sucesso!",
                Data = ResponseMappingExtensions.BuildSongResponse(song),
            });
        }
Пример #3
0
        private async Task <Models.User> RetrieveAuthor(Models.Post post)
        {
            var userCollection = MongoWrapper.Database.GetCollection <Models.User>(nameof(User));

            var userFilterBuilder = new FilterDefinitionBuilder <Models.User>();
            var userFilter        = userFilterBuilder.And
                                    (
                userFilterBuilder.Eq(u => u._id, post.Poster._id),
                GeneralUtils.NotDeactivated(userFilterBuilder)
                                    );

            var userProjectionBuilder = new ProjectionDefinitionBuilder <Models.User>();
            var userProjection        = userProjectionBuilder
                                        .Include(m => m._id)
                                        .Include(m => m.FullName)
                                        .Include(m => m.Avatar)
                                        .Include(m => m.Phone)
                                        .Include(m => m.StartDate)
                                        .Include(m => m.Email)
                                        .Include(m => m.Address)
                                        .Include("_t");

            return((await userCollection.FindAsync(userFilter, new FindOptions <Models.User>
            {
                Limit = 1,
                AllowPartialResults = true,
                Projection = userProjection
            })).SingleOrDefault());
        }
Пример #4
0
        public static async Task <string> GetCustomerEmailAsync(string domain)
        {
            try
            {
                if (_server == null)
                {
                    InitiateConnection();
                }

                var websiteCollection     = _kitsuneDB.GetCollection <KitsuneWebsiteCollection>(KLM_Constants.KitsuneWebsiteCollection);
                var websiteUserCollection = _kitsuneDB.GetCollection <KitsuneWebsiteUserCollection>(KLM_Constants.KitsuneWebsiteUserCollection);

                var project = new ProjectionDefinitionBuilder <KitsuneWebsiteUserCollection>();
                domain = domain.Trim(' ').ToUpper();

                var websiteId = await websiteCollection.Find(x => x.WebsiteUrl.Equals(domain),
                                                             new FindOptions { MaxTime = TimeSpan.FromMilliseconds(KLM_Constants.MongoQueryMaxtimeOut) }).Project(x => x._id).FirstOrDefaultAsync();

                if (websiteId != null)
                {
                    var user = await websiteUserCollection.Find(x => x.WebsiteId == websiteId,
                                                                new FindOptions { MaxTime = TimeSpan.FromMilliseconds(KLM_Constants.MongoQueryMaxtimeOut) }).FirstOrDefaultAsync();

                    return(user?.Contact?.Email);
                }
            }
            catch (Exception ex)
            {
            }
            return(null);
        }
Пример #5
0
        public async Task <string> FilterMovies(int yearLowerBand, int yearUpperBand)
        {
            var movies = new List <BsonDocument>();

            var projectionBuilder = new ProjectionDefinitionBuilder <BsonDocument>();
            var projection        = projectionBuilder
                                    .Include("awards")
                                    .Include("genres")
                                    .Include("plot")
                                    .Include("rated")
                                    .Include("title")
                                    .Include("year")
                                    .Exclude("_id");

            var filterBuilder = new FilterDefinitionBuilder <BsonDocument>();
            var filter        = filterBuilder.Gte("year", yearLowerBand) & filterBuilder.Lte("year", yearUpperBand);

            using (IAsyncCursor <BsonDocument> documents = await _database.GetCollection <BsonDocument>("movies").FindAsync(filter))
            {
                while (documents.MoveNext())
                {
                    movies.AddRange(documents.Current);
                }
            }

            return(movies.ToJson());
        }
        public async Task <T> GetDocumentWithSpecificFieldsAsync(string objectIdString, string[] projectionFields)
        {
            // TODO:Mohit Use FilterDefinitionBuilder - as the class is created for specific purpose

            var filter = new BsonDocument();

            filter.Add("_id", objectIdString);

            var projBuilder = new ProjectionDefinitionBuilder <T>();

            ProjectionDefinition <T>[] projections = new ProjectionDefinition <T> [projectionFields.Length];
            for (int i = 0; i < projectionFields.Length; i++)
            {
                var prof = projBuilder.Include(projectionFields[i]);
                projections[i] = prof;
            }

            var projectionDefinition = projBuilder.Combine(projections);
            var resultList           = await this.Collection.Find(filter).Project <T>(projectionDefinition).ToListAsync();

            //var resultList = await collection.Find(filter).ToListAsync();

            if (resultList.Count > 0)
            {
                return(resultList[0]);
            }
            else
            {
                return(null);
            }
        }
Пример #7
0
        public List <BsonDocument> getSatinfo()  //for combox 下拉显示

        {
            List <BsonDocument> satinfoList = new List <BsonDocument>();

            col = MongoDBHelper <SatInfomation> .Init();


            //创建约束生成器
            FilterDefinitionBuilder <BsonDocument> builder = Builders <BsonDocument> .Filter;

            ProjectionDefinitionBuilder <BsonDocument> builderProjection = Builders <BsonDocument> .Projection;
            //Exclude  不包含某元素
            ProjectionDefinition <BsonDocument> projection = builderProjection.Include("SatName").Exclude("_id");

            try
            {
                satinfoList = col.Find <BsonDocument>(builder.Empty).Project(projection).ToList();

                //foreach (var item in result)
                //{
                //    //取出整条值
                //    Console.WriteLine(item[0]);
                //}
            }

            catch (Exception e)
            {
                Console.WriteLine("mongodb连接失败" + e.Message); //只是输出终端显示 异常信息
                //throw;  //这是主动抛出异常 使程序停止
            }
            return(satinfoList);
        }
Пример #8
0
        private int getHighestID()
        {
            int rval = 0;

            rotateCollection();
            BsonDocument query = new BsonDocument();

            //TODO Refactor the query for 3.0 driver
            BsonDocument limits = new BsonDocument("$gt", new BsonDocument("w", workerID));

            limits.Add("$lt", new BsonDocument("w", workerID + 1));

            query.Add("_id", limits);

            var projection = new ProjectionDefinitionBuilder <BsonDocument>()
                             .Include("_id");
            var sort = new SortDefinitionBuilder <BsonDocument>()
                       .Descending("_id");
            BsonDocument myDoc = coll.Find(query)
                                 .Project(projection)
                                 .Sort(sort)
                                 .FirstOrDefault();

            if (myDoc != null)
            {
                BsonDocument id = (BsonDocument)myDoc.GetValue("_id");
                rval = id.GetValue("i").AsInt32 + 1;
            }
            return(rval);
        }
        public async Task <dynamic> Post([FromBody] PasswordRecoveryRequest requestBody)
        {
            this.EnsureModelValidation();

            var collection = MongoWrapper.Database.GetCollection <Models.User>(nameof(User));

            var projectionBuilder = new ProjectionDefinitionBuilder <Models.User>();
            var projection        = projectionBuilder
                                    .Include(u => u._id)
                                    .Include(u => u.Email)
                                    .Include(u => u.FullName)
                                    .Include("_t");

            var filterBuilder = new FilterDefinitionBuilder <Models.User>();
            var filter        = filterBuilder.And(
                filterBuilder.Eq(u => u.Email, requestBody.Email),
                GeneralUtils.NotDeactivated(filterBuilder)
                );

            var user = (await collection.FindAsync(filter, new FindOptions <Models.User>
            {
                Limit = 1,
                Projection = projection,
            })).SingleOrDefault();

            await EmailUtils.SendPasswordRecoveryEmail(MongoWrapper, SmtpConfiguration, user);

            return(new ResponseBody
            {
                Code = ResponseCode.GenericSuccess,
                Data = null,
                Message = "Um código foi enviado para o e-mail! Este código permite a redefinição para uma senha gerada automaticamente.",
                Success = true,
            });
        }
Пример #10
0
        public List <T> FindAll <T>(string collectionName)
        {
            List <T> result = new List <T>();
            ProjectionDefinition <T, T> prjection = new ProjectionDefinitionBuilder <T>().Exclude("_id");

            result = this._database.GetCollection <T>(collectionName).Find(Builders <T> .Filter.Empty).Project(prjection).ToList();
            return(result);
        }
Пример #11
0
        /// <summary>
        ///  查询数据
        /// </summary>
        /// <typeparam name="T">类型格式</typeparam>
        /// <param name="collectionName">表名称</param>
        /// <param name="filter">查询条件</param>
        /// <param name="sort">排序条件</param>
        /// <param name="skip">开始索引</param>
        /// <param name="limit">获取数据条数</param>
        /// <returns>List</returns>
        public List <T> Find <T>(string collectionName, FilterDefinition <T> filter, SortDefinition <T> sort, int skip = 0, int limit = 50)
        {
            List <T> result = new List <T>();
            ProjectionDefinition <T, T> project = new ProjectionDefinitionBuilder <T>().Exclude("_id");

            result = this._database.GetCollection <T>(collectionName).Find(filter).Project(project).Skip(skip).Limit(limit).Sort(sort).ToList();
            return(result);
        }
Пример #12
0
 private LabMongo()
     : base()
 {
     this.FilterBuiler = Builders<MReport>.Filter;
     this.UpdateBuiler = Builders<MReport>.Update;
     this.ProjectionBuiler = Builders<MReport>.Projection;
     this.LisMDB = MClient.GetDatabase(MongoDBName);
 }
        public void PipelineDefinitionCanBeBuild()
        {
            var selectArguments = "id, test.subtest, product.price.tax as tax";
            JsonPipelineStageDefinition <BsonDocument, BsonDocument> stage = null;

            Assert.That(() => stage = ProjectionDefinitionBuilder.Build <BsonDocument>(selectArguments), Throws.Nothing);
            Assert.That(stage, Is.Not.Null);
            Assert.That(stage.Json, Is.EqualTo("{ $project : { \"id\" : true, \"test_subtest\" : \"$test.subtest\", \"tax\" : \"$product.price.tax\" } }"));
        }
Пример #14
0
        protected virtual ProjectionDefinition <T> CreateProjectionDefinition(
            ProjectionParams projection, ProjectionDefinitionBuilder <T> projectionBuilder)
        {
            projection = projection ?? new ProjectionParams();

            return(projectionBuilder.Combine(
                       projection.Select(field => projectionBuilder.Include(field))
                       ).Exclude(InternalIdFieldName));
        }
Пример #15
0
        /// <summary>
        ///  查询数据
        /// </summary>
        /// <typeparam name="T">类型格式</typeparam>
        /// <param name="collectionName">表名称</param>
        /// <param name="filter">查询条件</param>
        /// <param name="project">映射条件</param>
        /// <returns>List</returns>
        public List <T> Find <T>(string collectionName, FilterDefinition <T> filter)
        {
            List <T> result = new List <T>();

            ProjectionDefinition <T, T> project = new ProjectionDefinitionBuilder <T>().Exclude("_id");

            result = this._database.GetCollection <T>(collectionName).Find(filter).ToList();//.Project(project)

            return(result);
        }
Пример #16
0
        /// <summary>
        /// 获得所有子文档
        /// 这种方法不能够获得指定条件的所有子文档,要想选出想要的子文档要用聚集操作
        /// </summary>
        public void QueryChildren()
        {
            //投影定义创建器:ProjectionDefinitionBuilder
            //用ProjectionDefinition过滤子文档
            ProjectionDefinitionBuilder <Model2> projBuilder = Builders <Model2> .Projection;
            ProjectionDefinition <Model2>        proj        = projBuilder.ElemMatch(listField => listField.Field2C, childfield => childfield.Field1B == 0);

            List <Model2> info = mongoDBService.List <Model2>(collectionName,
                                                              m => m.Field2A == "2" && m.Field2B == DateTime.Parse("2018-01-21T16:00:00.000Z"), proj);
        }
Пример #17
0
        private IEnumerable <TModel> FindAll(FilterDefinition <TModel> filter, QueryOptions <TModel> options)
        {
            ProjectionDefinition <TModel> projection = null;

            foreach (var field in options.Fields)
            {
                if (projection == null)
                {
                    projection = new ProjectionDefinitionBuilder <TModel>().Include(field);
                }
                else
                {
                    projection = projection.Include(field);
                }
            }

            SortDefinition <TModel> sortDefinition = null;
            var builder = new SortDefinitionBuilder <TModel>();

            if (options.SortAscending != null)
            {
                sortDefinition = builder.Ascending(options.SortAscending);
            }
            if (options.SortDescending != null)
            {
                sortDefinition = builder.Descending(options.SortDescending);
            }

            IFindFluent <TModel, TModel> result = null;

            if (projection == null)
            {
                result = Collection.Find(filter);
            }
            else
            {
                result = Collection.Find(filter).Project <TModel>(projection);
            }

            if (options.Skip.HasValue)
            {
                result.Skip(options.Skip.Value);
            }
            if (options.Take.HasValue)
            {
                result.Limit(options.Take);
            }

            if (sortDefinition != null)
            {
                result.Sort(sortDefinition);
            }

            return(result.ToEnumerable());
        }
Пример #18
0
        public async Task <AvgCost> FindAsync(string customer, string symbol)
        {
            var projectionDef = new ProjectionDefinitionBuilder <AvgCost>().Exclude(x => x.History);
            var findOptions   = new FindOptions <AvgCost, AvgCost>()
            {
                Projection = projectionDef
            };
            var cursor = await _collection.FindAsync(x => x.Customer == customer && x.Symbol == symbol, findOptions);

            return(await cursor.FirstOrDefaultAsync());
        }
Пример #19
0
 /// <summary>
 /// 内嵌文档分页
 /// </summary>
 public void SunPageList()
 {
     //投影定义创建器:ProjectionDefinitionBuilder
     //用ProjectionDefinition过滤子文档
     ProjectionDefinitionBuilder <Model2> projBuilder = Builders <Model2> .Projection;
     //Include :确定要包含哪些字段值(即给哪些字段赋值)
     //Slice:获得子文档集合分片,第一个参数field指取出的子文档集合,第二各参数skip指跳过多少个子文档,第三个参数limit取出多少个
     ProjectionDefinition <Model2> proj = projBuilder.Include(m => m.Field2C).Slice(m => m.Field2C, 1, 3);
     //过滤条件是Field2A=2
     Model2 doc = mongoDBService.SubdocumentPageList <Model2>(collectionName, m => m.Field2A == "2", proj);
 }
        public async Task <UserEntity> Handle(GetUserByIdQuery request, CancellationToken cancellationToken)
        {
            var projection = new ProjectionDefinitionBuilder <UserEntity>()
                             .Include(x => x.Id)
                             .Include(x => x.UserName)
                             .Include(x => x.FriendlyName);

            return(await _userCollection
                   .Find(x => x.Id == request.Id)
                   .Project <UserEntity>(projection)
                   .FirstOrDefaultAsync(cancellationToken));
        }
Пример #21
0
        public BaseRepository()
        {
            string connectionString = ConfigurationManager.AppSettings["mongodb"];
            var    client           = new MongoClient(connectionString);
            var    database         = client.GetDatabase(DbName);

            Collection = database.GetCollection <T>(typeof(T).Name);
            Filter     = new FilterDefinitionBuilder <T>();
            Update     = new UpdateDefinitionBuilder <T>();
            Sort       = new SortDefinitionBuilder <T>();
            Projection = new ProjectionDefinitionBuilder <T>();
        }
        public async Task <UserEntity> Handle(GetUserByEmailQuery request, CancellationToken cancellationToken)
        {
            var projection = new ProjectionDefinitionBuilder <UserEntity>()
                             .Include(x => x.Id)
                             .Include(x => x.EmailAddress)
                             .Include(x => x.Password)
                             .Include(x => x.UserName)
                             .Include(x => x.Roles);

            return(await _userCollection
                   .Find(x => x.EmailAddress == request.EmailAddress)
                   .Project <UserEntity>(projection)
                   .FirstOrDefaultAsync(cancellationToken));
        }
        public async Task <dynamic> IncrementById(string userId, string songId)
        {
            var userCollection = MongoWrapper.Database.GetCollection <Models.Musician>(nameof(Models.User));

            var songFilterBuilder = new FilterDefinitionBuilder <Models.Song>();
            var songFilter        = songFilterBuilder.And
                                    (
                songFilterBuilder.Eq(s => s._id, new ObjectId(songId)),
                GeneralUtils.NotDeactivated(songFilterBuilder)
                                    );

            var userFilterBuilder = new FilterDefinitionBuilder <Models.Musician>();
            var userFilter        = userFilterBuilder.And
                                    (
                userFilterBuilder.Eq(u => u._id, new ObjectId(userId)),
                GeneralUtils.NotDeactivated(userFilterBuilder),
                userFilterBuilder.ElemMatch(s => s.Songs, songFilter)
                                    );

            var userProjectionBuilder = new ProjectionDefinitionBuilder <Models.Musician>();
            var userProjection        = userProjectionBuilder
                                        .ElemMatch(m => m.Songs, songFilter);

            var userUpdateBuilder = new UpdateDefinitionBuilder <Models.Musician>();
            var userUpdate        = userUpdateBuilder.Inc($"{nameof(Musician.Songs).WithLowercaseFirstCharacter()}.$.{nameof(Models.Song.TimesPlayed).WithLowercaseFirstCharacter()}", 1);

            var user = await userCollection.FindOneAndUpdateAsync(userFilter, userUpdate, new FindOneAndUpdateOptions <Models.Musician>
            {
                Projection     = userProjection,
                ReturnDocument = ReturnDocument.Before,
            });

            if (user == null)
            {
                Response.StatusCode = (int)HttpStatusCode.NotFound;
                return(new ResponseBody
                {
                    Code = ResponseCode.NotFound,
                    Success = false,
                    Message = "Música não encontrada!",
                });
            }

            return(new ResponseBody
            {
                Code = ResponseCode.GenericSuccess,
                Success = true,
                Message = "Contador incrementado com sucesso!",
            });
        }
Пример #24
0
        private async Task <IEnumerable <MetascoredAdvertisement> > FetchAds(string metaPhrase, GeoJsonPoint <GeoJson3DGeographicCoordinates> position = null)
        {
            var adProjectionBuilder = new ProjectionDefinitionBuilder <MetascoredAdvertisement>();
            var adProjection        = adProjectionBuilder
                                      .MetaTextScore(nameof(MetascoredAdvertisement.MetaScore).WithLowercaseFirstCharacter())
                                      .Include(ad => ad._id)
                                      .Include(ad => ad.Title)
                                      .Include(ad => ad.Text)
                                      .Include(ad => ad.Poster)
                                      .Include(ad => ad.FileReferences)
            ;

            return(await FetchEntities(metaPhrase, adProjection, MongoWrapper.Database.GetCollection <MetascoredAdvertisement>(nameof(Models.Advertisement)), 100, 5, position));
        }
Пример #25
0
        private BsonDocument simpleKeyQuery()
        {
            // Key Query
            rotateCollection();
            BsonDocument query = new BsonDocument();
            int          range = sequence * testOpts.workingset / 100;
            int          rest  = sequence - range;

            int recordno = rest + getNextVal(range);

            query.Add("_id",
                      new BsonDocument("w", workerID).Add("i", recordno));
            DateTime      starttime = DateTime.Now;
            BsonDocument  myDoc;
            List <String> projFields = new List <String>(testOpts.numFields);

            if (testOpts.projectFields == 0)
            {
                myDoc = coll.Find(query).FirstOrDefault();
            }
            else
            {
                int numProjFields = (testOpts.projectFields <= testOpts.numFields) ? testOpts.projectFields : testOpts.numFields;
                int i             = 0;
                while (i < numProjFields)
                {
                    projFields.Add("fld" + i);
                    i++;
                }
                var projection = new ProjectionDefinitionBuilder <BsonDocument>();
                foreach (var field in projFields)
                {
                    projection.Include(field);
                }
                myDoc = coll.Find(query)
                        .Project <BsonDocument>(projection.Combine())
                        .FirstOrDefault();
            }

            if (myDoc != null)
            {
                var taken = (DateTime.Now - starttime).TotalMilliseconds;
                if (taken > testOpts.slowThreshold)
                {
                    testResults.RecordSlowOp("keyqueries", 1);
                }
                testResults.RecordOpsDone("keyqueries", 1);
            }
            return(myDoc);
        }
Пример #26
0
        public static async Task <ProjectDetails> GetProjectDetailsAsync(string projectId, KitsuneRequestUrlType kitsuneRequestUrlType = KitsuneRequestUrlType.PRODUCTION)
        {
            try
            {
                if (_server == null)
                {
                    InitiateConnection();
                }

                var projectionBuilder = new ProjectionDefinitionBuilder <ProductionKitsuneProject>();
                var projection        = projectionBuilder.Include(x => x.BucketNames)
                                        .Include(x => x.SchemaId)
                                        .Include(x => x.Version)
                                        .Include(x => x.Components)
                                        .Include(x => x.RuntimeOptimization)
                                        .Include(x => x._id)
                                        .Include(x => x.ProjectId)
                                        .Include(x => x.UserEmail)
                                        .Include(x => x.CompilerVersion);

                var filter = Builders <ProductionKitsuneProject> .Filter.Eq(document => document.ProjectId, projectId);

                var collectionName = KLM_Constants.KitsuneProjectProductionCollection;
                if (kitsuneRequestUrlType == KitsuneRequestUrlType.DEMO || kitsuneRequestUrlType == KitsuneRequestUrlType.PREVIEW)
                {
                    collectionName = KLM_Constants.KitsuneProjectCollection;
                }

                var productionKitsuneProjectsCOllection = _kitsuneDB.GetCollection <ProductionKitsuneProject>(collectionName);
                var result = await productionKitsuneProjectsCOllection.Find(filter,
                                                                            new FindOptions { MaxTime = TimeSpan.FromMilliseconds(KLM_Constants.MongoQueryMaxtimeOut) }).Project <ProductionKitsuneProject>(projection).FirstOrDefaultAsync();

                return(new ProjectDetails()
                {
                    BucketNames = result.BucketNames,
                    SchemaId = result.SchemaId,
                    Version = result.Version,
                    Components = result.Components,
                    DeveloperEmail = result.UserEmail,
                    RuntimeOptimization = result.RuntimeOptimization,
                    ProjectId = result.ProjectId,
                    CompilerVersion = result.CompilerVersion
                });
            }
            catch (Exception ex)
            {
            }
            return(null);
        }
Пример #27
0
        private void rangeQuery()
        {
            // Key Query
            rotateCollection();
            BsonDocument query      = new BsonDocument();
            var          projection = new ProjectionDefinitionBuilder <BsonDocument>();
            int          recordno   = getNextVal(sequence);

            query.Add("_id", new BsonDocument("$gt", new BsonDocument("w",
                                                                      workerID).Add("i", recordno)));
            DateTime starttime = new DateTime();
            IAsyncCursor <BsonDocument> cursor;

            if (testOpts.projectFields == 0)
            {
                cursor = coll.Find(query)
                         .Limit(testOpts.rangeDocs)
                         .ToCursor();
            }
            else
            {
                int numProjFields = (testOpts.projectFields <= testOpts.numFields) ? testOpts.projectFields : testOpts.numFields;
                for (int i = 0; i < numProjFields; i++)
                {
                    projection.Include("fld" + i);
                }
                cursor = coll.Find(query)
                         .Project <BsonDocument>(projection.Combine())
                         .Limit(testOpts.rangeDocs)
                         .ToCursor();
            }
            while (cursor.MoveNext())
            {
                var batch = cursor.Current;
                foreach (var doc in batch)
                {
                    // Consume the cursor
                }
            }
            cursor.Dispose();

            var taken = (DateTime.Now - starttime).TotalMilliseconds;

            if (taken > testOpts.slowThreshold)
            {
                testResults.RecordSlowOp("rangequeries", 1);
            }
            testResults.RecordOpsDone("rangequeries", 1);
        }
Пример #28
0
        private async Task <IEnumerable <MetascoredPost> > FetchPosts(string metaPhrase, GeoJsonPoint <GeoJson3DGeographicCoordinates> position = null)
        {
            var postProjectionBuilder = new ProjectionDefinitionBuilder <MetascoredPost>();
            var postProjection        = postProjectionBuilder
                                        .MetaTextScore(nameof(MetascoredPost.MetaScore).WithLowercaseFirstCharacter())
                                        .Include(post => post._id)
                                        .Include(post => post.Title)
                                        .Include(post => post.Text)
                                        .Include(post => post.Poster)
                                        .Include(post => post.Likes)
                                        .Include(post => post.FileReferences)
                                        .Include(post => post.Comments)
            ;

            return(await FetchEntities(metaPhrase, postProjection, MongoWrapper.Database.GetCollection <MetascoredPost>(nameof(Models.Post)), 30, 10, position));
        }
        public async Task <LicenseEntity> Handle(GetLicenseByIdQuery request, CancellationToken cancellationToken)
        {
            var filter = new FilterDefinitionBuilder <LicenseEntity>()
                         .Eq(x => x.Id, request.LicenseId);

            var projection = new ProjectionDefinitionBuilder <LicenseEntity>()
                             .Include(x => x.Id)
                             .Include(x => x.UserId)
                             .Include($"{nameof(LicenseEntity.Products)}.{nameof(LicenseProductEntity.Name)}")
                             .Include($"{nameof(LicenseEntity.Products)}.{nameof(LicenseProductEntity.Expiration)}");

            return(await _licenseCollection
                   .Find(filter)
                   .Project <LicenseEntity>(projection)
                   .FirstOrDefaultAsync(cancellationToken));
        }
        public async Task <List <T> > GetAllDocumentsWithSpecificFieldsAsync(string[] projectionFields)
        {
            var filter      = new BsonDocument();
            var projBuilder = new ProjectionDefinitionBuilder <T>();

            ProjectionDefinition <T>[] projections = new ProjectionDefinition <T> [projectionFields.Length];
            for (int i = 0; i < projectionFields.Length; i++)
            {
                var prof = projBuilder.Include(projectionFields[i]);
                projections[i] = prof;
            }

            var projectionDefinition = projBuilder.Combine(projections);
            var result = await this.Collection.Find(filter).Project <T>(projectionDefinition).ToListAsync();

            return(result);
        }
    public static ProjectionDefinition <T> IncludeAll <T>(this ProjectionDefinitionBuilder <T> projection,
                                                          params string[] fields)
    {
        ProjectionDefinition <T> project = null;

        foreach (string columnName in fields)
        {
            if (project == null)
            {
                project = Builders <T> .Projection.Include(columnName);
            }
            else
            {
                project = project.Include(columnName);
            }
        }
        return(project);
    }