public async Task <TEntity> GetSingleAsync( FilterDefinition <TEntity> filter, ProjectionDefinition <TEntity, TEntity> projection = null) { var options = new FindOptions <TEntity, TEntity> { Projection = projection }; var cursor = await _collection.FindAsync(filter, options); return(await cursor.FirstOrDefaultAsync()); }
/// <summary> /// Get list of objects of type T from db only for reading /// </summary> /// <param name="filter">Filter a sequense of values based on a predicate</param> /// <param name="projection"></param> public async Task <T> GetAsync(Expression <Func <T, bool> > filter, ProjectionDefinition <T> projection = null) { var query = DbContext.GetCollection <T>().Find(filter); if (projection != null) { query.Options.Projection = projection; } var result = await query.FirstOrDefaultAsync(); return(result); }
public Result <IList <T> > GetAllDocuments <T>(string documentname, ProjectionDefinition <T> fields) { try { var filter = Builders <T> .Filter.Empty; return(_database.GetCollection <T>(documentname).Find(filter).Project <T>(fields).ToList()); } catch (Exception ex) { return(Result.Failure <IList <T> >(ex.Message)); } }
/// <summary> /// Get document of type T from db by Id for reading /// </summary> /// <param name="id"></param> /// <param name="projection"></param> /// <typeparam name="T"></typeparam> /// <returns></returns> public async Task <T> GetAsync(string id, ProjectionDefinition <T> projection = null) { var query = DbContext.GetCollection <T>().Find(_ => _.Id.Equals(id)); if (projection != null) { query.Options.Projection = projection; } var result = await query.FirstOrDefaultAsync(); return(result); }
protected ProjectionDefinition <Role, Role> GetRoleProjections() { var roleProjBuilder = Builders <Role> .Projection; roleProjBuilder.Include(x => x.Id); roleProjBuilder.Include(x => x.Name); roleProjBuilder.Include(x => x.Consumer); roleProjBuilder.Include(x => x.Description); roleProjBuilder.Include(x => x.Status); ProjectionDefinition <Role, Role> proj = roleProjBuilder.As <Role>(); return(proj); }
public IDocumentFinderQueryBuilder Select <T1, T2>(Expression <Func <T1, T2> > property) where T1 : class { if (Projection == null) { Projection = Builders <Document> .Projection.Include(new StringFieldDefinition <Document, T2>(DocumentPropertyPathProvider.GetFor(property))); } else { Projection = Projection.Include(new StringFieldDefinition <Document, T2>(DocumentPropertyPathProvider.GetFor(property))); } return(this); }
public async Task <TEntity> GetByIdAsync( string id, ProjectionDefinition <TEntity, TEntity> projection = null) { if (id.IsInvalidObjectId()) { return(default(TEntity)); } var filter = Builders <TEntity> .Filter.Eq(e => e.Id, id); return(await GetSingleAsync(filter, projection)); }
public IEnumerable <BsonDocument> GetPageList(FilterDefinition <BsonDocument> eqs, IEnumerable <string> excludeFields, IEnumerable <string> includeFields, Dictionary <string, string> sorts, int pageIndex, int pageSize, ref long count) { count = MongoCollection.CountDocuments(eqs); var find = MongoCollection.Find(eqs); //排除字段 if (excludeFields != null && excludeFields.Count() > 0) { ProjectionDefinition <BsonDocument> exclude = null; foreach (string ex in excludeFields) { if (exclude == null) { exclude = Builders <BsonDocument> .Projection.Exclude(ex); } exclude = exclude.Exclude(ex); } find = find.Project(exclude); } //包含字段 if (includeFields != null && includeFields.Count() > 0) { ProjectionDefinition <BsonDocument> include = null; foreach (string ex in includeFields) { if (include == null) { include = Builders <BsonDocument> .Projection.Include(ex); } include = include.Include(ex); } find = find.Project(include); } if (sorts != null && sorts.Count > 0) { foreach (var item in sorts) { if (item.Value == "asc") { find = find.SortBy(sort => sort[item.Key]); } if (item.Value == "desc") { find = find.SortByDescending(sort => sort[item.Key]); } } } return(find.Skip((pageIndex - 1) * pageSize) .Limit(pageSize) .ToEnumerable()); }
public IList <T> GetPagedDocumentsByFilter(FilterDefinition <T> filter, ProjectionDefinition <T> fields, SortDefinition <T> sort, int pageIndex, int pageSize) { IList <T> result; if (pageIndex != 0 && pageSize != 0) { result = _database.GetCollection <T>(_documentName).Find(filter).Project <T>(fields).Sort(sort).Skip(pageSize * (pageIndex - 1)).Limit(pageSize).ToList(); } else { result = _database.GetCollection <T>(_documentName).Find(filter).Project <T>(fields).Sort(sort).ToList(); } return(result); }
public IQueryable <T> DocDanhSach(FilterDefinition <T> dieuKienLoc, ProjectionDefinition <T> fields, int?soluong = null) { if (dieuKienLoc == null && fields == null && soluong != null) { return(_collection.Find(new BsonDocument()).Limit(soluong).ToList().AsQueryable()); } if (soluong == null) { return(_collection.Find(dieuKienLoc).Project <T>(fields).ToList().AsQueryable()); } var value = (int)soluong; return(_collection.Find(dieuKienLoc).Project <T>(fields).Limit(value).ToList().AsQueryable()); }
public virtual async Task <long> CountAllAsync( Expression <Func <TEntity, bool> > filter = null, Func <Expression <Func <TEntity, bool> >, List <TEntity> > whenNoExists = null, ProjectionDefinition <TEntity, TEntity> projection = null) { var cursor = filter == null?_collection.Find(t => true) : _collection.Find(filter); if (projection != null) { cursor = cursor.Project(projection); } return(await cursor.CountDocumentsAsync()); }
public List <Funcionario> ListarTudo() { // Funcionario _funcionario; ProjectionDefinition <Funcionario> _projection = Builders <Funcionario> .Projection.Exclude("_id"); FilterDefinition <Funcionario> _filter = Builders <Funcionario> .Filter.Empty; List <Funcionario> lista = _colecao.Find(_filter).ToList <Funcionario>(); /* IEnumerable<Funcionario> query = from f in _funcionarios.AsQueryable<Funcionario>() * select f; */ return(lista); }
public Task <IAsyncCursor <string> > GetArticleIdsForBlog(string blogId) { Guard.Argument(blogId, nameof(blogId)).NotNull().NotEmpty(); FilterDefinition <Article> filterDefinition = Builders <Article> .Filter.Eq(x => x.BlogId, blogId); ProjectionDefinition <Article> projectionDefinition = Builders <Article> .Projection.Include(x => x.ArticleId); FindOptions <Article, string> findOptions = new FindOptions <Article, string> { Projection = projectionDefinition }; return(_articleCollection.FindAsync(filterDefinition, findOptions)); }
/// <inheritdoc/> protected virtual async ValueTask <IEnumerable <TProject> > EsSearchGetAsync <TProject>( ProjectionDefinition <T, TProject> projection, int page, int?pageSize, SortDefinition <T> orderby , FilterDefinition <T> filter = null, string query = null) { filter ??= Builders <T> .Filter.Empty; if (!string.IsNullOrWhiteSpace(query) && orderby == null) { var response = await client.SearchAsync <TEsSearch>(s => s .Index(index).Query(q => q .QueryString(sq => sq.Fields(f => f.Field(f => f.SearchAbleString)) .Query(query))).Sort(s => s.Descending("_score")) .Skip(page *pageSize).Take(pageSize)); var sr = response.Documents.Select(d => d.Id); var re = await collection.FindIgnoreCase(Builders <T> .Filter.Eq(t => t.IsDeleted, false)& filter & filterBuilder.In(e => e.Id, sr)) .Project(projection) .Skip(page * pageSize).Limit(pageSize) .ToListAsync(); try { List <TProject> fin = new List <TProject>(); foreach (var item in sr) { var article = re.Where(a => ((IGuidEntity)a).Id == item).FirstOrDefault(); if (article != null) { fin.Add(article); } } return(fin); } catch (Exception) { return(re); } } if (!string.IsNullOrEmpty(query)) { var tokens = await client.Indices .AnalyzeAsync(s => s.Analyzer(analyzer).Text(query)); filter &= filterBuilder.AnyIn(a => a.Tokens, tokens.Tokens.Select(t => t.Token)); } return(await collection.FindIgnoreCase(Builders <T> .Filter.Eq(t => t.IsDeleted, false)& filter) .Project(projection) .Sort(orderby ?? Builders <T> .Sort.Descending("CreateTime")).Skip(page * pageSize).Limit(pageSize) .ToListAsync()); }
/// <summary> /// 根据条件获取实体 /// </summary> /// <param name="filter">查询条件</param> /// <param name="sort">排序</param> /// <param name="projection"></param> /// <param name="hint">hint索引</param> /// <param name="readPreference">访问设置</param> /// <returns></returns> public TEntity Get(FilterDefinition <TEntity> filter , ProjectionDefinition <TEntity, TEntity> projection = null , SortDefinition <TEntity> sort = null, BsonValue hint = null , ReadPreference readPreference = null) { if (filter == null) { filter = Builders <TEntity> .Filter.Empty; } var option = base.CreateFindOptions(projection, sort, limit: 1, hint: hint); var result = base.GetCollection(readPreference).FindSync(filter, option); return(result.FirstOrDefault()); }
/// <summary> /// Initializes a new instance of the <see cref="StreamFetcher{T}"/> class. /// </summary> /// <param name="stream">The <see cref="IMongoCollection{TDocument}" />.</param> /// <param name="filter">The <see cref="FilterDefinitionBuilder{TDocument}" />.</param> /// <param name="sequenceNumberExpression">The <see cref="Expression{T}" /> for getting the sequence number from the stored event.</param> /// <param name="eventToStreamEvent">The <see cref="ProjectionDefinition{TSource, TProjection}" /> for projecting the stored event to a <see cref="Store.Streams.StreamEvent" />.</param> /// <param name="eventToArtifact">The <see cref="ProjectionDefinition{TSource, TProjection}" /> for projecting the stored event to <see cref="Artifact" />.</param> /// <param name="partitionIdExpression">The <see cref="Expression{T}" /> for getting the <see cref="Guid" /> for the Partition Id from the stored event.</param> public StreamFetcher( IMongoCollection <TEvent> stream, FilterDefinitionBuilder <TEvent> filter, Expression <Func <TEvent, ulong> > sequenceNumberExpression, ProjectionDefinition <TEvent, Store.Streams.StreamEvent> eventToStreamEvent, ProjectionDefinition <TEvent, Artifact> eventToArtifact, Expression <Func <TEvent, Guid> > partitionIdExpression = default) { _stream = stream; _filter = filter; _sequenceNumberExpression = sequenceNumberExpression; _eventToStreamEvent = eventToStreamEvent; _eventToArtifact = eventToArtifact; _partitionIdExpression = partitionIdExpression; }
public T SelectOne <T>(string collectionName, ProjectionDefinition <T> projection, Expression <Func <T, bool> > filter) { if (mDatabase == null) { throw new Exception("MongoDB database was null!!!"); } var collection = mDatabase.GetCollection <T>(collectionName); var result = collection.Find(filter).Project(projection).FirstOrDefault(); if (result == null) { return(default(T)); } return(BsonSerializer.Deserialize <T>(result)); }
/// <summary> /// 根据id获取实体 /// </summary> /// <param name="id"></param> /// <param name="includeFieldExp">查询字段表达式</param> /// <param name="sortExp">排序表达式</param> /// <param name="sortType">排序方式</param> /// <param name="hint">hint索引</param> /// <param name="readPreference">访问设置</param> /// <returns></returns> public async Task <TEntity> GetAsync(TKey id, Expression <Func <TEntity, object> > includeFieldExp = null, Expression <Func <TEntity, object> > sortExp = null, SortType sortType = SortType.Ascending, BsonValue hint = null, ReadPreference readPreference = null) { FilterDefinition <TEntity> filter = Builders <TEntity> .Filter.Eq <TKey>((TEntity x) => x.ID, id); ProjectionDefinition <TEntity, TEntity> projection = null; if (includeFieldExp != null) { projection = base.IncludeFields <TEntity>(includeFieldExp); } FindOptions <TEntity, TEntity> options = base.CreateFindOptions <TEntity>(projection, sortExp, sortType, 1, 0, hint); IAsyncCursor <TEntity> cursor = await base.GetCollection(readPreference).FindAsync <TEntity>(filter, options, default(CancellationToken)).ConfigureAwait(false); return(await cursor.FirstOrDefaultAsync(default(CancellationToken)).ConfigureAwait(false)); }
/// <summary> /// 根据条件获取实体 /// </summary> /// <param name="filter"></param> /// <param name="sort"></param> /// <param name="projection"></param> /// <param name="hint">hint索引</param> /// <param name="readPreference">访问设置</param> /// <returns></returns> public async Task <TEntity> GetAsync(FilterDefinition <TEntity> filter , ProjectionDefinition <TEntity, TEntity> projection = null , SortDefinition <TEntity> sort = null, BsonValue hint = null , ReadPreference readPreference = null) { if (filter == null) { filter = Builders <TEntity> .Filter.Empty; } var option = base.CreateFindOptions(projection, sort: sort, limit: 1, hint: hint); var result = await base.GetCollection(readPreference).FindAsync(filter, option).ConfigureAwait(false); return(await result.FirstOrDefaultAsync().ConfigureAwait(false)); }
public List <Models.Permit.Choose> GetAllForChoose() { var filter = Builders <Entities.Permit> .Filter.Empty; var projections = new ProjectionDefinition <Entities.Permit>[] { Builders <Entities.Permit> .Projection.Include(nameof(Entities.Permit.ID)), Builders <Entities.Permit> .Projection.Include(nameof(Entities.Permit.Code)), Builders <Entities.Permit> .Projection.Include(nameof(Entities.Permit.Name)) }; var projection = Builders <Entities.Permit> .Projection.Combine(projections); var list = this.Collection.Find(filter).Project(projection).As <Entities.Permit>().ToList(); var result = AutoMapper.Mapper.Map <List <Models.Permit.Choose> >(list); return(result); }
/// <inheritdoc /> public async Task <bool> TryDrop(ProjectionDefinition projection, CancellationToken token) { ThrowIfShouldNotPersistFor(projection); try { var collection = GetCollectionNameFor(projection); await _storage.Database.DropCollectionAsync(collection, token).ConfigureAwait(false); return(true); } catch (MongoWaitQueueFullException) { return(false); } }
private Task <int> IncrementSeq() { FilterDefinition <Counter> filter = Builders <Counter> .Filter.Eq(counter => counter.Key, Urls); UpdateDefinition <Counter> update = Builders <Counter> .Update.Inc(counter => counter.Seq, 1); ProjectionDefinition <Counter, int> projection = Builders <Counter> .Projection.Expression(counter => counter.Seq); return(_db.GetCollection <Counter>(Counters) .FindOneAndUpdateAsync(filter, update, new FindOneAndUpdateOptions <Counter, int> { IsUpsert = true, Projection = projection })); }
/// <summary> /// 根据条件获取获取列表 /// </summary> /// <param name="filter"></param> /// <param name="projection"></param> /// <param name="sort"></param> /// <param name="limit"></param> /// <param name="skip"></param> /// <param name="hint">hint索引</param> /// <param name="readPreference">访问设置</param> /// <returns></returns> public List <TEntity> GetList(FilterDefinition <TEntity> filter , ProjectionDefinition <TEntity, TEntity> projection = null , SortDefinition <TEntity> sort = null , int limit = 0, int skip = 0, BsonValue hint = null , ReadPreference readPreference = null) { if (filter == null) { filter = Builders <TEntity> .Filter.Empty; } var option = base.CreateFindOptions(projection, sort, limit, skip, hint: hint); var result = base.GetCollection(readPreference).FindSync(filter, option); return(result.ToList()); }
/// <inheritdoc/> public virtual async ValueTask <IEnumerable <TProject> > GetAsync <TProject>( ProjectionDefinition <T, TProject> projection, int page, int?pageSize , FilterDefinition <T> filter = null, string query = null) { filter ??= Builders <T> .Filter.Empty; var stringsearch = query == null ? Builders <T> .Filter.Empty : Builders <T> .Filter.Text(query, new TextSearchOptions() { CaseSensitive = false, DiacriticSensitive = false, Language = "none" }); return(await collection.FindIgnoreCase(Builders <T> .Filter.Eq(t => t.IsDeleted, false)& filter& stringsearch) .Project(projection).Skip(page * pageSize).Limit(pageSize) .ToListAsync()); }
public async Task <IEnumerable <TEntity> > GetAllAsync( FilterDefinition <TEntity> filter = null, SortDefinition <TEntity> sort = null, ProjectionDefinition <TEntity, TEntity> projection = null) { filter = filter ?? Builders <TEntity> .Filter.Empty; var options = new FindOptions <TEntity, TEntity> { Sort = sort, Projection = projection }; var cursor = await _collection.FindAsync(filter, options); return(await cursor.ToListAsync()); }
public virtual async Task <PagedList <TEntity> > GetAllPagedAsync(Restriction restriction, Order order, Page page, Expression <Func <TEntity, bool> > filter = null, Func <Expression <Func <TEntity, bool> >, PagedList <TEntity> > whenNoExists = null, ProjectionDefinition <TEntity, TEntity> projection = null) { var cursor = filter == null?_collection.Find(t => true) : _collection.Find(filter); if (projection != null) { cursor = cursor.Project(projection); } var result = await cursor.ToListAsync(); return(result.AsQueryable().Order(order).Paged(page, order, restriction)); }
private ProjectionDefinition createAggregatedProjectionDefinition(string projectionName) { var definition = new ProjectionDefinition(); definition.ProjectionName = projectionName; definition.FeedName = orderType; definition.Aggregated = true; definition.Handlers = new List <Handler>(); definition.Handlers.Add(new Handler(eventType: "OrderPlaced", functions: new List <Function>() { new Function(functionProperty: "add", targetSelector: "$.projection.orderAmount", eventSelector: "$.event.orderAmount"), new Function(functionProperty: "inc", targetSelector: "$.projection.orderCount") })); return(definition); }
/// <summary> /// 查询所有数据(指定列) /// </summary> /// <returns></returns> public List <ResultT> List <T, ResultT>() { var resultType = typeof(ResultT); var projectionList = new List <ProjectionDefinition <T> >(); foreach (var p in resultType.GetProperties()) { projectionList.Add(Builders <T> .Projection.Include(p.Name)); } ProjectionDefinition <T> projectionDefinition = Builders <T> .Projection.Combine(projectionList); IMongoCollection <T> collection = database.GetCollection <T>(typeof(T).Name); var filter = new BsonDocument(); return(collection.Find(filter).Project <ResultT>(projectionDefinition).ToList().Distinct().ToList()); }
private static bool HasUnassignedOptions(MongoConnection mongoConnection, Type optionType) { IMongoCollection <OptionBase> datas = mongoConnection.Database.GetCollection <OptionBase>(optionType.Name); FilterDefinition <OptionBase> filter = Builders <OptionBase> .Filter.Eq(data => data.Schedule.WorkerId, null); ProjectionDefinition <OptionBase, ObjectId> projection = Builders <OptionBase> .Projection.Include(option => option._id); IFindFluent <OptionBase, ObjectId> find = datas.Find(filter).Project(projection); find.Limit(1); Task <ObjectId> dataTask = find.SingleOrDefaultAsync(); return(dataTask.Result != null); }
internal static ProjectionDefinition <T, TProjection> CombineWithRequiredProps <TProjection>(ProjectionDefinition <T, TProjection> userProjection) { if (userProjection == null) { throw new InvalidOperationException("Please use .Project() method before .IncludeRequiredProps()"); } if (requiredPropsProjection is null) { requiredPropsProjection = "{_id:1}"; var props = typeof(T) .GetProperties() .Where(p => p.IsDefined(typeof(BsonRequiredAttribute), false)); if (!props.Any()) { throw new InvalidOperationException("Unable to find any entity properties marked with [BsonRequired] attribute!"); } FieldAttribute attr; foreach (var p in props) { attr = p.GetCustomAttribute <FieldAttribute>(); if (attr is null) { requiredPropsProjection = requiredPropsProjection.Include(p.Name); } else { requiredPropsProjection = requiredPropsProjection.Include(attr.ElementName); } } } ProjectionDefinition <T> userProj = userProjection.Render( BsonSerializer.LookupSerializer <T>(), BsonSerializer.SerializerRegistry).Document; return(Builders <T> .Projection.Combine(new[] { requiredPropsProjection, userProj })); }
public BookController(IMongoService mongoService) { books = mongoService.Database.GetCollection<Book>("books"); projection = Builders<Book>.Projection.Include("Name").Include("Pictures"); }