Ejemplo n.º 1
1
 public IFindFluent<BsonDocument, BsonDocument> Query(FilterDefinition<BsonDocument> filter, int? skip = null, int? limit = null)
 {
     return _mongoCollection
         .Find(filter)
         .Skip(skip)
         .Limit(limit);
 }
Ejemplo n.º 2
1
        public FilterDefinition<IdeaEntity> IdeaFilterQuery(FilterDefinition<IdeaEntity> filter, IdeaFilter ideaFilter)
        {
            if (!String.IsNullOrWhiteSpace(ideaFilter.Username))
            {
                filter = filter & IdeaFilterQuery(ideaFilter);
            }

            return filter;
        }
Ejemplo n.º 3
1
        public QueryBuilder GetQueryBuilder(string collectionName)
        {
            var result = new QueryBuilder();
            var client = new MongoClient("mongodb://localhost:27017");
            var db = client.GetDatabase("hra");
            var items = db.GetCollection<DataCollectionMetadata>("collectionMetadata");
            var collectionItems = db.GetCollection<BsonDocument>("incumbent");

            FilterDefinition<DataCollectionMetadata> filter = new BsonDocument("_id", "incumbent");
            var md = items.Find<DataCollectionMetadata>(filter);
            var metadata = md.SingleAsync().Result;
            var tasks = new List<Task<IAsyncCursor<string>>>();
            metadata.Filters.ForEach(f =>
            {
                var filterDefinition = new FilterDefinition();

                filterDefinition.Column = f;

                    FieldDefinition<BsonDocument, string> field = f.ColumnName;

                    var dd = Task<IAsyncCursor<string>>.Factory.StartNew(() =>
                    {
                        var t = collectionItems.DistinctAsync<string>(field, new BsonDocument());
                        t.GetAwaiter().OnCompleted(() =>
                        {
                            t.Result.ForEachAsync((z) =>
                            {
                                filterDefinition.AvailableFilterValues.Add(new FilterValue { Key = z, Value = z });
                            });
                        });
                        return t.Result;
                    });
                    tasks.Add(dd);

                result.AvailableFilters.Add(filterDefinition);
            });
            result.AvailableSlicers = metadata.Dimensions.Select(x => new DimensionDefinition {Column = x, IsDefault = x.IsDefault}).ToList();
            //refactor available operations
            result.AvailableMeasures =
                metadata.Measures.Select(
                    x => new MeasureDefinition {Column = x, Operation = AggregateOperations.Average, IsDefault=x.IsDefault}).ToList();
            Task.WaitAll(tasks.ToArray());
            return result;
        }
        async private Task<IEnumerable<BsonDocument>> Find(FilterDefinition<BsonDocument> filter)
        {
            var documents = default(IEnumerable<BsonDocument>);

            if(filter != null)
            { 
                documents = await CollectionInformation?.Find(filter).ToListAsync();
            }

            return documents;
        }
Ejemplo n.º 5
0
        static async Task findDocuments(IMongoCollection<student> collection, FilterDefinition<student> searchFilter)
        {

            //Option 1: for iterting over many documents on the server.
            Console.WriteLine("--------------------------------------------------------------------");
            ///using (var cursor = await collection.Find(searchFilter).Sort("{student_id:1, scores.type:1}").ToCursorAsync())
            using (var cursor = await collection.Find(searchFilter).ToCursorAsync())
            {
                using (StreamWriter w = File.AppendText("c:\\data\\hw31.txt"))
                {
                    while (await cursor.MoveNextAsync())  //iterate over each batch
                    {
                        foreach (var doc in cursor.Current)
                        {
                            double minHWScore = 100.0;
                            ///string text = i + " :=> sid: " + doc.student_id + ":" + doc.scores.ToString();
                            List<studentscore> thisStudentScores = doc.scores.ToList();
                            foreach (studentscore s in thisStudentScores)
                            {
                                if (s.type.Equals("homework"))
                                {
                                    if (s.score < minHWScore)
                                    {
                                        minHWScore = s.score;
                                    }
                                }
                            }

                            studentscore[] newScores = thisStudentScores.Where((x) => x.score != minHWScore).ToArray<studentscore>();
                            doc.scores = newScores.ToArray<studentscore>();
                            var filter = Builders<student>.Filter.Eq("Id", doc.Id);
                            await collection.ReplaceOneAsync(filter, doc);

                            Console.WriteLine(doc.ToString());
                            w.WriteLine(doc.ToString());
                            
                            /**
                            if (i % 4 == 0)
                            {
                                Console.WriteLine("lowest score for " + doc.student_id + " is " + doc.score);
                                w.WriteLine("lowest score for " + doc.student_id + " is " + doc.score);
                                await collection.DeleteOneAsync(a => a.Id == doc.Id);
                            }
                            i++;
                            **/
                        }
                    }
                }
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Gets all documents which fulfill a filter condition.
        /// </summary>
        /// <param name="collectionName">Name of collection</param>
        /// <param name="filter">Filter condition</param>
        /// <returns>List of all documents which fulfill filter's conditions</returns>
        public static async Task<List<BsonDocument>> GetAll(String collectionName, FilterDefinition<BsonDocument> filter)
        {
            List<BsonDocument> results;
            IAsyncCursor<BsonDocument> cursor;
            IMongoCollection<BsonDocument> collection;

            try
            {
                collection = GetCollection(collectionName);
                cursor = await collection.FindAsync(filter);
                results = cursor.ToListAsync().Result;

                return results;
            }
            catch (Exception ex)
            {
                throw new Exception("Error getting data from collection." + Environment.NewLine + Environment.NewLine + ex.Message);
            }
        }
Ejemplo n.º 7
0
        private async Task <List <MongoContentEntity> > FindContentsAsync(ClrQuery query, FilterDefinition <MongoContentEntity> filter)
        {
            var result =
                Collection.Find(filter)
                .QueryLimit(query)
                .QuerySkip(query)
                .ToListAsync();

            return(await result);
        }
        /// <summary>
        /// Updates a document.
        /// </summary>
        /// <typeparam name="TDocument">The type representing a Document.</typeparam>
        /// <typeparam name="TKey">The type of the primary key for a Document.</typeparam>
        /// <typeparam name="TField">The type of the field to update.</typeparam>
        /// <param name="session">The client session.</param>
        /// <param name="filter">The filter for the update.</param>
        /// <param name="field">The field to update.</param>
        /// <param name="value">The value of the field.</param>
        /// <param name="partitionKey">The optional partition key.</param>
        /// <param name="cancellationToken">The optional cancellation token.</param>
        /// <returns></returns>
        public virtual bool UpdateOne <TDocument, TKey, TField>(IClientSessionHandle session, FilterDefinition <TDocument> filter, Expression <Func <TDocument, TField> > field, TField value, string partitionKey = null, CancellationToken cancellationToken = default(CancellationToken))
            where TDocument : IDocument <TKey>
            where TKey : IEquatable <TKey>
        {
            var collection = string.IsNullOrEmpty(partitionKey) ? GetCollection <TDocument, TKey>() : GetCollection <TDocument, TKey>(partitionKey);
            var updateRes  = collection.UpdateOne(session, filter, Builders <TDocument> .Update.Set(field, value), cancellationToken: cancellationToken);

            return(updateRes.ModifiedCount == 1);
        }
        public FilterDefinition <BsonDocument> BuildQuery(FhirRequest request)
        {
            if (request.IsIdQuery)
            {
                return(BuildQuery(request.Id));
            }

            var builder = Builders <BsonDocument> .Filter;
            var filters = new List <FilterDefinition <BsonDocument> >();

            if (request.QueryParameters == null || request.QueryParameters.Count() == 0)
            {
                return(FilterDefinition <BsonDocument> .Empty);
            }

            var searchQuery = SearchParams.FromUriParamList(request.QueryParameters);

            var modelParams = SearchParameters.Where(s => s.Resource.Equals(request.StrResourceType) && request.AllowedParameters.Contains(s.Name));

            StructureDefinition profile = null;

            if (!string.IsNullOrEmpty(request.ProfileUri))
            {
                try
                {
                    profile = (StructureDefinition)GetResourceProfile(request.ProfileUri);
                }
                catch
                {
                    throw new HttpFhirException("Failed to parse fhir type for search query.", OperationOutcomeFactory.CreateInternalError($"Failed to parse fhir type of {request.StrResourceType} for search query."));
                }
            }



            foreach (var param in modelParams)
            {
                var paramName = param.Name;

                var criteria = searchQuery.Parameters.FirstOrDefault(x => (!x.Item1.Contains(".") && x.Item1.Equals(paramName)) || (x.Item1.Contains(".") && x.Item1.StartsWith(paramName)));

                if (criteria == null)
                {
                    continue;
                }

                var paramDef = profile?.Snapshot?.Element.FirstOrDefault(e => e.Path.Equals($"{request.StrResourceType}.{paramName}"));

                var paramVal = criteria.Item2;

                if (param.Type.Equals(SearchParamType.Reference) && !string.IsNullOrEmpty(paramVal))
                {
                    if (paramName.Contains("custodian")) //temp allow custodian.identifier
                    {
                        paramName = "custodian";
                    }

                    filters.Add(builder.Eq($"{paramName}.reference", paramVal));
                    continue;
                }

                if (param.Type.Equals(SearchParamType.Token) && !string.IsNullOrEmpty(paramVal))
                {
                    var isCodeOnly = !paramVal.Contains("|");
                    var sysVal     = paramVal.Split('|');

                    //expand these to allow other token types
                    var valType   = "value";
                    var sysType   = "system";
                    var arrayPath = "";

                    //extend for other types
                    if (paramDef != null)
                    {
                        if (paramDef.Type.FirstOrDefault(t => t.Code.Equals(FHIRAllTypes.CodeableConcept.ToString())) != null)
                        {
                            valType = "code";

                            var tokenCodingDef = profile.Snapshot?.Element.FirstOrDefault(e => e.Path.Equals($"{request.StrResourceType}.{paramName}.coding"));

                            if (tokenCodingDef == null)
                            {
                                continue;
                            }

                            int?   minVal = tokenCodingDef.Min;
                            string maxVal = tokenCodingDef.Max;

                            if (tokenCodingDef.Base != null)
                            {
                                minVal = tokenCodingDef.Base.Min;
                                maxVal = tokenCodingDef.Base.Max;
                            }

                            int max      = 0;
                            var isMaxint = !string.IsNullOrWhiteSpace(maxVal) && int.TryParse(maxVal, out max);

                            //Assuming tokenCodingDef is a CodeableConcept.coding element
                            if (minVal.HasValue && minVal.Value >= 0 && (maxVal.Equals("*") || isMaxint && max > 0))
                            {
                                arrayPath = ".coding";
                            }
                        }

                        if (paramDef.Type.FirstOrDefault(t => t.Code.Equals(FHIRAllTypes.Code.ToString().ToLowerInvariant())) != null)
                        {
                            valType = "";

                            var tokenCodingDef = profile.Snapshot?.Element.FirstOrDefault(e => e.Path.Equals($"{request.StrResourceType}.{paramName}"));

                            if (tokenCodingDef == null)
                            {
                                continue;
                            }

                            int?   minVal = tokenCodingDef.Min;
                            string maxVal = tokenCodingDef.Max;

                            if (tokenCodingDef.Base != null)
                            {
                                minVal = tokenCodingDef.Base.Min;
                                maxVal = tokenCodingDef.Base.Max;
                            }

                            int max      = 0;
                            var isMaxint = !string.IsNullOrWhiteSpace(maxVal) && int.TryParse(maxVal, out max);

                            //Assuming tokenCodingDef is a code element
                            if (minVal.HasValue && minVal.Value >= 0 && (maxVal.Equals("*") || isMaxint && max > 0))
                            {
                                arrayPath = "";
                            }
                        }
                    }


                    // NRLS Hack - NRLS allows masterIdentifier but not identifier document element
                    // Could extend this to create an OR for masterIdentifier || identifier
                    if (request.StrResourceType.Equals(ResourceType.DocumentReference.ToString()) && paramName.Equals("identifier"))
                    {
                        paramName = "masterIdentifier";
                    }


                    if (sysVal.Length == 1 && isCodeOnly)
                    {
                        if (string.IsNullOrEmpty(arrayPath))
                        {
                            var valTypeSegment = string.IsNullOrEmpty(valType) ? "" : $".{valType}";
                            filters.Add(builder.Eq($"{paramName}{valTypeSegment}", sysVal.ElementAt(0)));
                        }
                        else
                        {
                            filters.Add(builder.ElemMatch($"{paramName}{arrayPath}", builder.Eq(valType, sysVal.ElementAt(0))));
                        }
                        continue;
                    }
                    else if (sysVal.Length == 2)
                    {
                        FilterDefinition <BsonDocument> sysValFilter = null;

                        if (!string.IsNullOrEmpty(sysVal.ElementAt(0)))
                        {
                            if (string.IsNullOrEmpty(arrayPath))
                            {
                                filters.Add(builder.Eq($"{paramName}.{sysType}", sysVal.ElementAt(0)));
                            }
                            else
                            {
                                sysValFilter = builder.Eq(sysType, sysVal.ElementAt(0));
                            }
                        }

                        if (!string.IsNullOrEmpty(sysVal.ElementAt(1)))
                        {
                            if (string.IsNullOrEmpty(arrayPath))
                            {
                                filters.Add(builder.Eq($"{paramName}.{valType}", sysVal.ElementAt(1)));
                            }
                            else
                            {
                                sysValFilter = sysValFilter & builder.Eq(valType, sysVal.ElementAt(1));
                            }
                        }

                        if (!string.IsNullOrEmpty(arrayPath) && sysValFilter != null)
                        {
                            filters.Add(builder.ElemMatch($"{paramName}{arrayPath}", sysValFilter));
                        }

                        continue;
                    }
                }
            }

            if (filters.Count() == 0)
            {
                return(FilterDefinition <BsonDocument> .Empty);
            }

            return(builder.And(filters));
        }
Ejemplo n.º 10
0
 public bool Exists(FilterDefinition <T> query)
 {
     return(Collection.CountDocuments(query) != 0);
 }
Ejemplo n.º 11
0
 public T GetOne(FilterDefinition <T> filter)
 {
     return(Collection.Find(filter).SingleOrDefault());
 }
Ejemplo n.º 12
0
        public async Task <IEnumerable <Product> > GetProductsByCategory(string category)
        {
            FilterDefinition <Product> filter = Builders <Product> .Filter.Eq(p => p.Category, category);

            return(await _context.Products.Find(filter).ToListAsync());
        }
        public static async Task <TItem> FirstOrDefaultAsync <TItem>(this IMongoCollection <TItem> collection, FilterDefinition <TItem> p, CancellationToken cancellationToken = default)
        {
            if (collection == null)
            {
                throw new ArgumentNullException(nameof(collection));
            }

            return(await(await collection.FindAsync(p, LimitOneOption <TItem>(), cancellationToken).ConfigureAwait(false)).FirstOrDefaultAsync().ConfigureAwait(false));
        }
Ejemplo n.º 14
0
        /// <inheritdoc />
        public async Task<IAsyncCursor<GridFSFileInfo>> FindAsync(FilterDefinition<GridFSFileInfo> filter, GridFSFindOptions options = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            Ensure.IsNotNull(filter, nameof(filter));
            options = options ?? new GridFSFindOptions();

            var operation = CreateFindOperation(filter, options);
            using (var binding = await GetSingleServerReadBindingAsync(cancellationToken).ConfigureAwait(false))
            {
                return await operation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false);
            }
        }
Ejemplo n.º 15
0
 public void DeleteOne(FilterDefinition <T> filter)
 {
     Collection.DeleteOneAsync(filter);
 }
Ejemplo n.º 16
0
        private QueryBuilder GetQueryBuilder()
        {
            var queryBuilder = new QueryBuilder();

            BsonClassMap.RegisterClassMap<DataCollectionMetadata>(cm =>
            {
                cm.AutoMap();
                cm.MapIdMember(c => c.CollectionName);

            });
            var client = new MongoClient("mongodb://localhost:27017");
            var db = client.GetDatabase("hra");
            var items = db.GetCollection<DataCollectionMetadata>("collectionMetadata");
            var collectionItems = db.GetCollection<BsonDocument>("incumbent");

            FilterDefinition<DataCollectionMetadata> filter = new BsonDocument("_id", "incumbent");
            var md = items.Find<DataCollectionMetadata>(filter);
            //var ct = md.CountAsync().Result;

            var metaData = md.SingleAsync().Result;
            var fValues = new List<String>();
            var tasks = new List<Task<IAsyncCursor<string>>>();
            metaData.Filters.ForEach(f =>
            {
                var filterDefinition = new FilterDefinition();

                filterDefinition.Column = f;

                FieldDefinition<BsonDocument, string> field = f.ColumnName;
                var dd = Task<IAsyncCursor<string>>.Factory.StartNew(() =>
                {
                    var t = collectionItems.DistinctAsync<string>(field, new BsonDocument());
                    t.GetAwaiter().OnCompleted(() =>
                    {
                        t.Result.ForEachAsync((z) =>
                        {
                            filterDefinition.AvailableFilterValues.Add(new FilterValue {Key = z, Value = z});
                        });
                    });
                    return t.Result;
                });

                tasks.Add(dd);
                queryBuilder.AvailableFilters.Add(filterDefinition);
            });

            Task.WaitAll(tasks.ToArray());
            Assert.IsFalse(queryBuilder.SelectedFilters.Any());

            var gd = new GroupDefinition();

            gd.Dimensions.Add(new DimensionDefinition
            {
                Column = new DataColumnMetadata { ColumnName = "Year", DataType = ColumnDataTypes.Int32 },
                IsDefault=true
            });

            var fd = new MeasureDefinition();
            fd.Column = new DataColumnMetadata {ColumnName = "Base_Pay", DataType = ColumnDataTypes.Double};
            fd.IsDefault = true;

            gd.Measures.Add(fd);
            return queryBuilder;
        }
Ejemplo n.º 17
0
 public void UpdateOne(FilterDefinition <T> filter, UpdateDefinition <T> update)
 {
     Collection.UpdateOneAsync(filter, update);
 }
Ejemplo n.º 18
0
 public async Task <T> FindOneAndUpdate(FilterDefinition <T> filter, UpdateDefinition <T> update, FindOneAndUpdateOptions <T> option)
 {
     return(await Collection.FindOneAndUpdateAsync(filter, update, option));
 }
Ejemplo n.º 19
0
 public IEnumerable <T> GetByFilterAsync(FilterDefinition <T> filter)
 {
     return(Collection.Find(filter).ToListAsync().Result);
 }
Ejemplo n.º 20
0
        private async Task<List<TestProjectReport>> GetFilteredData(FilterDefinition<TestProjectReport> filter)
        {
            var data = await Collection.Find(filter).ToListAsync();

            return data;
        }
        public static async Task <IEnumerable <TItem> > WhereAsync <TItem>(this IMongoCollection <TItem> collection, FilterDefinition <TItem> p, CancellationToken cancellationToken = default)
        {
            if (collection == null)
            {
                throw new ArgumentNullException(nameof(collection));
            }

            return((await collection.FindAsync(p).ConfigureAwait(false)).ToEnumerable());
        }
Ejemplo n.º 22
0
        MatchDefinition GetMatchDefinition()
        {
            var mf = new FilterDefinition
            {
                Column = new DataColumnMetadata { ColumnName = "Job_Family", DataType = ColumnDataTypes.String }

            };
            mf.AvailableFilterValues.Add(new FilterValue {Key = "Executive", Value = "Executive", Active=true});
            var matchDefinition = new MatchDefinition();
            matchDefinition.Filters.Add(mf);

            return matchDefinition;
        }
Ejemplo n.º 23
0
        private async Task <IEnumerable <T> > Find <T>(ObjectSerializer Serializer, IMongoCollection <BsonDocument> Collection,
                                                       int Offset, int MaxCount, FilterDefinition <BsonDocument> BsonFilter, params string[] SortOrder)
        {
            IFindFluent <BsonDocument, BsonDocument> ResultSet = Collection.Find <BsonDocument>(BsonFilter);

            if (SortOrder.Length > 0)
            {
                SortDefinition <BsonDocument> SortDefinition = null;

                foreach (string SortBy in SortOrder)
                {
                    if (SortDefinition == null)
                    {
                        if (SortBy.StartsWith("-"))
                        {
                            SortDefinition = Builders <BsonDocument> .Sort.Descending(Serializer.ToShortName(SortBy.Substring(1)));
                        }
                        else
                        {
                            SortDefinition = Builders <BsonDocument> .Sort.Ascending(Serializer.ToShortName(SortBy));
                        }
                    }
                    else
                    {
                        if (SortBy.StartsWith("-"))
                        {
                            SortDefinition = SortDefinition.Descending(Serializer.ToShortName(SortBy.Substring(1)));
                        }
                        else
                        {
                            SortDefinition = SortDefinition.Ascending(Serializer.ToShortName(SortBy));
                        }
                    }
                }

                ResultSet = ResultSet.Sort(SortDefinition);
            }

            if (Offset > 0)
            {
                ResultSet = ResultSet.Skip(Offset);
            }

            if (MaxCount < int.MaxValue)
            {
                ResultSet = ResultSet.Limit(MaxCount);
            }

            IAsyncCursor <BsonDocument> Cursor = await ResultSet.ToCursorAsync();

            LinkedList <T>          Result = new LinkedList <T>();
            BsonDeserializationArgs Args   = new BsonDeserializationArgs()
            {
                NominalType = typeof(T)
            };

            while (await Cursor.MoveNextAsync())
            {
                foreach (BsonDocument Document in Cursor.Current)
                {
                    BsonDocumentReader         Reader  = new BsonDocumentReader(Document);
                    BsonDeserializationContext Context = BsonDeserializationContext.CreateRoot(Reader);

                    T Obj = (T)Serializer.Deserialize(Context, Args);
                    Result.AddLast(Obj);
                }
            }

            return(Result);
        }
Ejemplo n.º 24
0
 public async Task<IEnumerable<User>> FindByFilter(FilterDefinition<User> filter)
 {
     return await _repository.FindByFilter(filter);
 }
Ejemplo n.º 25
0
        private FilterDefinition <BsonDocument> Convert(Filter Filter, ObjectSerializer Serializer)
        {
            if (Filter is FilterChildren FilterChildren)
            {
                Filter[] ChildFilters = FilterChildren.ChildFilters;
                int      i, c = ChildFilters.Length;
                FilterDefinition <BsonDocument>[] Children = new FilterDefinition <BsonDocument> [c];

                for (i = 0; i < c; i++)
                {
                    Children[i] = this.Convert(ChildFilters[i], Serializer);
                }

                if (Filter is FilterAnd)
                {
                    return(Builders <BsonDocument> .Filter.And(Children));
                }
                else if (Filter is FilterOr)
                {
                    return(Builders <BsonDocument> .Filter.Or(Children));
                }
                else
                {
                    throw this.UnknownFilterType(Filter);
                }
            }
            else if (Filter is FilterChild FilterChild)
            {
                FilterDefinition <BsonDocument> Child = this.Convert(FilterChild.ChildFilter, Serializer);

                if (Filter is FilterNot)
                {
                    return(Builders <BsonDocument> .Filter.Not(Child));
                }
                else
                {
                    throw this.UnknownFilterType(Filter);
                }
            }
            else if (Filter is FilterFieldValue FilterFieldValue)
            {
                object Value          = FilterFieldValue.Value;
                string FieldName      = Serializer.ToShortName(FilterFieldValue.FieldName, ref Value);
                bool   IsDefaultValue = Serializer.IsDefaultValue(FilterFieldValue.FieldName, Value);

                if (Filter is FilterFieldEqualTo)
                {
                    if (IsDefaultValue)
                    {
                        return(Builders <BsonDocument> .Filter.Eq <string>(FieldName, null));
                    }
                    else if (Value is string)
                    {
                        return(Builders <BsonDocument> .Filter.Eq <string>(FieldName, (string)Value));
                    }
                    else if (Value is int)
                    {
                        return(Builders <BsonDocument> .Filter.Eq <int>(FieldName, (int)Value));
                    }
                    else if (Value is long)
                    {
                        return(Builders <BsonDocument> .Filter.Eq <long>(FieldName, (long)Value));
                    }
                    else if (Value is double)
                    {
                        return(Builders <BsonDocument> .Filter.Eq <double>(FieldName, (double)Value));
                    }
                    else if (Value is bool)
                    {
                        return(Builders <BsonDocument> .Filter.Eq <bool>(FieldName, (bool)Value));
                    }
                    else if (Value is DateTime)
                    {
                        return(Builders <BsonDocument> .Filter.Eq <DateTime>(FieldName, (DateTime)Value));
                    }
                    else if (Value is ObjectId)
                    {
                        return(Builders <BsonDocument> .Filter.Eq <ObjectId>(FieldName, (ObjectId)Value));
                    }
                    else
                    {
                        throw this.UnhandledFilterValueDataType(Serializer.ValueType.FullName, FieldName, Value);
                    }
                }
                else if (Filter is FilterFieldNotEqualTo)
                {
                    if (IsDefaultValue)
                    {
                        return(Builders <BsonDocument> .Filter.Ne <string>(FieldName, null));
                    }
                    else if (Value is string)
                    {
                        return(Builders <BsonDocument> .Filter.Ne <string>(FieldName, (string)Value));
                    }
                    else if (Value is int)
                    {
                        return(Builders <BsonDocument> .Filter.Ne <int>(FieldName, (int)Value));
                    }
                    else if (Value is long)
                    {
                        return(Builders <BsonDocument> .Filter.Ne <long>(FieldName, (long)Value));
                    }
                    else if (Value is double)
                    {
                        return(Builders <BsonDocument> .Filter.Ne <double>(FieldName, (double)Value));
                    }
                    else if (Value is bool)
                    {
                        return(Builders <BsonDocument> .Filter.Ne <bool>(FieldName, (bool)Value));
                    }
                    else if (Value is DateTime)
                    {
                        return(Builders <BsonDocument> .Filter.Ne <DateTime>(FieldName, (DateTime)Value));
                    }
                    else if (Value is ObjectId)
                    {
                        return(Builders <BsonDocument> .Filter.Ne <ObjectId>(FieldName, (ObjectId)Value));
                    }
                    else
                    {
                        throw this.UnhandledFilterValueDataType(Serializer.ValueType.FullName, FieldName, Value);
                    }
                }
                else if (Filter is FilterFieldGreaterThan)
                {
                    if (Value is string)
                    {
                        return(Builders <BsonDocument> .Filter.Gt <string>(FieldName, (string)Value));
                    }
                    else if (Value is int)
                    {
                        return(Builders <BsonDocument> .Filter.Gt <int>(FieldName, (int)Value));
                    }
                    else if (Value is long)
                    {
                        return(Builders <BsonDocument> .Filter.Gt <long>(FieldName, (long)Value));
                    }
                    else if (Value is double)
                    {
                        return(Builders <BsonDocument> .Filter.Gt <double>(FieldName, (double)Value));
                    }
                    else if (Value is bool)
                    {
                        return(Builders <BsonDocument> .Filter.Gt <bool>(FieldName, (bool)Value));
                    }
                    else if (Value is DateTime)
                    {
                        return(Builders <BsonDocument> .Filter.Gt <DateTime>(FieldName, (DateTime)Value));
                    }
                    else if (Value is ObjectId)
                    {
                        return(Builders <BsonDocument> .Filter.Gt <ObjectId>(FieldName, (ObjectId)Value));
                    }
                    else
                    {
                        throw this.UnhandledFilterValueDataType(Serializer.ValueType.FullName, FieldName, Value);
                    }
                }
                else if (Filter is FilterFieldGreaterOrEqualTo)
                {
                    if (IsDefaultValue)
                    {
                        return(this.Convert(new FilterOr(new FilterFieldGreaterThan(FieldName, Value),
                                                         new FilterFieldEqualTo(FieldName, Value)), Serializer));
                    }
                    else if (Value is string)
                    {
                        return(Builders <BsonDocument> .Filter.Gte <string>(FieldName, (string)Value));
                    }
                    else if (Value is int)
                    {
                        return(Builders <BsonDocument> .Filter.Gte <int>(FieldName, (int)Value));
                    }
                    else if (Value is long)
                    {
                        return(Builders <BsonDocument> .Filter.Gte <long>(FieldName, (long)Value));
                    }
                    else if (Value is double)
                    {
                        return(Builders <BsonDocument> .Filter.Gte <double>(FieldName, (double)Value));
                    }
                    else if (Value is bool)
                    {
                        return(Builders <BsonDocument> .Filter.Gte <bool>(FieldName, (bool)Value));
                    }
                    else if (Value is DateTime)
                    {
                        return(Builders <BsonDocument> .Filter.Gte <DateTime>(FieldName, (DateTime)Value));
                    }
                    else if (Value is ObjectId)
                    {
                        return(Builders <BsonDocument> .Filter.Gte <ObjectId>(FieldName, (ObjectId)Value));
                    }
                    else
                    {
                        throw this.UnhandledFilterValueDataType(Serializer.ValueType.FullName, FieldName, Value);
                    }
                }
                else if (Filter is FilterFieldLesserThan)
                {
                    if (Value is string)
                    {
                        return(Builders <BsonDocument> .Filter.Lt <string>(FieldName, (string)Value));
                    }
                    else if (Value is int)
                    {
                        return(Builders <BsonDocument> .Filter.Lt <int>(FieldName, (int)Value));
                    }
                    else if (Value is long)
                    {
                        return(Builders <BsonDocument> .Filter.Lt <long>(FieldName, (long)Value));
                    }
                    else if (Value is double)
                    {
                        return(Builders <BsonDocument> .Filter.Lt <double>(FieldName, (double)Value));
                    }
                    else if (Value is bool)
                    {
                        return(Builders <BsonDocument> .Filter.Lt <bool>(FieldName, (bool)Value));
                    }
                    else if (Value is DateTime)
                    {
                        return(Builders <BsonDocument> .Filter.Lt <DateTime>(FieldName, (DateTime)Value));
                    }
                    else if (Value is ObjectId)
                    {
                        return(Builders <BsonDocument> .Filter.Lt <ObjectId>(FieldName, (ObjectId)Value));
                    }
                    else
                    {
                        throw this.UnhandledFilterValueDataType(Serializer.ValueType.FullName, FieldName, Value);
                    }
                }
                else if (Filter is FilterFieldLesserOrEqualTo)
                {
                    if (IsDefaultValue)
                    {
                        return(this.Convert(new FilterOr(new FilterFieldLesserThan(FieldName, Value),
                                                         new FilterFieldEqualTo(FieldName, Value)), Serializer));
                    }
                    else if (Value is string)
                    {
                        return(Builders <BsonDocument> .Filter.Lte <string>(FieldName, (string)Value));
                    }
                    else if (Value is int)
                    {
                        return(Builders <BsonDocument> .Filter.Lte <int>(FieldName, (int)Value));
                    }
                    else if (Value is long)
                    {
                        return(Builders <BsonDocument> .Filter.Lte <long>(FieldName, (long)Value));
                    }
                    else if (Value is double)
                    {
                        return(Builders <BsonDocument> .Filter.Lte <double>(FieldName, (double)Value));
                    }
                    else if (Value is bool)
                    {
                        return(Builders <BsonDocument> .Filter.Lte <bool>(FieldName, (bool)Value));
                    }
                    else if (Value is DateTime)
                    {
                        return(Builders <BsonDocument> .Filter.Lte <DateTime>(FieldName, (DateTime)Value));
                    }
                    else if (Value is ObjectId)
                    {
                        return(Builders <BsonDocument> .Filter.Lte <ObjectId>(FieldName, (ObjectId)Value));
                    }
                    else
                    {
                        throw this.UnhandledFilterValueDataType(Serializer.ValueType.FullName, FieldName, Value);
                    }
                }
                else
                {
                    throw this.UnknownFilterType(Filter);
                }
            }
            else
            {
                if (Filter is FilterFieldLikeRegEx FilterFieldLikeRegEx)
                {
                    return(Builders <BsonDocument> .Filter.Regex(Serializer.ToShortName(FilterFieldLikeRegEx.FieldName),
                                                                 FilterFieldLikeRegEx.RegularExpression));
                }
                else
                {
                    throw this.UnknownFilterType(Filter);
                }
            }
        }
Ejemplo n.º 26
0
        public async Task <IEnumerable <Product> > GetProductsByName(string name)
        {
            FilterDefinition <Product> filter = Builders <Product> .Filter.Eq(p => p.Name, name);

            return(await _context.Products.Find(filter).ToListAsync());
        }
        public User FindById(int id)
        {
            FilterDefinition <User> filter = Builders <User> .Filter.Eq("_id", id);

            return(userCollection.Find(filter).FirstOrDefault());
        }
        public async Task <Tuple <IEnumerable <T>, long> > GetAsync(int currentPage, int pageSize, FilterDefinition <T> filter = null, SortDefinition <T> sort = null)
        {
            var  query      = Collection.Find <T>(filter);
            long totalCount = await query.CountDocumentsAsync();

            if (sort == null)
            {
                sort = Builders <T> .Sort.Descending(x => x.CreationDate);
            }
            List <T> records = await query.Sort(sort).Skip((currentPage - 1) * pageSize).Limit(pageSize).ToListAsync();

            return(new Tuple <IEnumerable <T>, long>(records, totalCount));
        }
        public User FindByUsername(string username)
        {
            FilterDefinition <User> filter = Builders <User> .Filter.Regex("username", new MongoDB.Bson.BsonRegularExpression("^" + username + "$", "i"));

            return(userCollection.Find(filter).FirstOrDefault());
        }
Ejemplo n.º 30
0
 public void Update(FilterDefinition <T> query, UpdateDefinition <T> update)
 {
     this.Collection.UpdateMany(query, update);
 }
        public User FindByEmail(string email)
        {
            FilterDefinition <User> filter = Builders <User> .Filter.Regex("email", new MongoDB.Bson.BsonRegularExpression("^" + email + "$", "i"));

            return(userCollection.Find(filter).FirstOrDefault());
        }
Ejemplo n.º 32
0
 public void Delete(FilterDefinition <T> query)
 {
     Collection.DeleteMany(query);
 }
        public Dictionary <int, User> FindByIds(IEnumerable <int> ids)
        {
            FilterDefinition <User> filter = Builders <User> .Filter.In("_id", ids);

            return(userCollection.Find(filter).ToEnumerable().ToDictionary(x => x.ID));
        }
Ejemplo n.º 34
0
 public DeleteFilterOperation(IMongoCollection <T> mongoCollection, FilterDefinition <T> filter)
 {
     _mongoCollection = mongoCollection;
     _filter          = filter;
 }
Ejemplo n.º 35
0
        public Task UpdateAsync(TKey id, TEntity item)
        {
            FilterDefinition <TEntity> filter = Builders <TEntity> .Filter.Eq("_id", id);

            return(Collection.ReplaceOneAsync(filter, item));
        }
Ejemplo n.º 36
0
 public static void Update <T>(this IMongoCollection <T> collection, FilterDefinition <T> filter, UpdateDefinition <T> update)
     where T : class
 {
     collection.FindOneAndUpdateAsync(filter, update).Wait();
 }
Ejemplo n.º 37
0
        /// <inheritdoc />
        public async Task<IAsyncCursor<GridFSFileInfo>> FindAsync(FilterDefinition<GridFSFileInfo> filter, GridFSFindOptions options = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            Ensure.IsNotNull(filter, nameof(filter));
            options = options ?? new GridFSFindOptions();

            var filesCollectionNamespace = GetFilesCollectionNamespace();
            var serializerRegistry = _database.Settings.SerializerRegistry;
            var fileInfoSerializer = serializerRegistry.GetSerializer<GridFSFileInfo>();
            var messageEncoderSettings = GetMessageEncoderSettings();
            var renderedFilter = filter.Render(fileInfoSerializer, serializerRegistry);
            var renderedSort = options.Sort == null ? null : options.Sort.Render(fileInfoSerializer, serializerRegistry);

            var operation = new FindOperation<GridFSFileInfo>(
                filesCollectionNamespace,
                fileInfoSerializer,
                messageEncoderSettings)
            {
                BatchSize = options.BatchSize,
                Filter = renderedFilter,
                Limit = options.Limit,
                MaxTime = options.MaxTime,
                NoCursorTimeout = options.NoCursorTimeout ?? false,
                Skip = options.Skip,
                Sort = renderedSort
            };

            using (var binding = await GetSingleServerReadBindingAsync(cancellationToken).ConfigureAwait(false))
            {
                return await operation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false);
            }
        }
 private BsonDocument FindOne(FilterDefinition<BsonDocument> filter)
 {
     var documents = Find(filter);
     return documents?.Result?.FirstOrDefault();
 }
Ejemplo n.º 39
0
 internal static Task <UpdateResult> UpdateAsync <T>(FilterDefinition <T> filter, UpdateDefinition <T> definition, UpdateOptions options, IClientSessionHandle session = null, string db = null, CancellationToken cancellation = default)
 {
     return(session == null
            ? Collection <T>(db).UpdateManyAsync(filter, definition, options, cancellation)
            : Collection <T>(db).UpdateManyAsync(session, filter, definition, options, cancellation));
 }
Ejemplo n.º 40
0
        /// <inheritdoc />
        public IAsyncCursor<GridFSFileInfo> Find(FilterDefinition<GridFSFileInfo> filter, GridFSFindOptions options = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            Ensure.IsNotNull(filter, nameof(filter));
            options = options ?? new GridFSFindOptions();

            var operation = CreateFindOperation(filter, options);
            using (var binding = GetSingleServerReadBinding(cancellationToken))
            {
                return operation.Execute(binding, cancellationToken);
            }
        }
 /// <summary>
 ///
 /// </summary>
 /// <typeparam name="T">文档类型</typeparam>
 /// <param name="filter">过滤器</param>
 /// <param name="options">设置</param>
 /// <param name="cancellationToken">标记</param>
 /// <returns></returns>
 public long CountDocuments <T>(FilterDefinition <T> filter, CountOptions options = null, CancellationToken cancellationToken = default) where T : BaseMongoEntity
 {
     return(Database.GetCollection <T>(typeof(T).Name).CountDocuments(filter, options, cancellationToken));
 }
Ejemplo n.º 42
0
        private FindOperation<GridFSFileInfo> CreateFindOperation(FilterDefinition<GridFSFileInfo> filter, GridFSFindOptions options)
        {
            var filesCollectionNamespace = GetFilesCollectionNamespace();
            var serializerRegistry = _database.Settings.SerializerRegistry;
            var fileInfoSerializer = serializerRegistry.GetSerializer<GridFSFileInfo>();
            var messageEncoderSettings = GetMessageEncoderSettings();
            var renderedFilter = filter.Render(fileInfoSerializer, serializerRegistry);
            var renderedSort = options.Sort == null ? null : options.Sort.Render(fileInfoSerializer, serializerRegistry);

            return new FindOperation<GridFSFileInfo>(
                filesCollectionNamespace,
                fileInfoSerializer,
                messageEncoderSettings)
            {
                BatchSize = options.BatchSize,
                Filter = renderedFilter,
                Limit = options.Limit,
                MaxTime = options.MaxTime,
                NoCursorTimeout = options.NoCursorTimeout ?? false,
                ReadConcern = GetReadConcern(),
                Skip = options.Skip,
                Sort = renderedSort
            };
        }
Ejemplo n.º 43
0
 /// <summary>
 /// Gets first documents from collections which fulfill filter conditions
 /// </summary>
 /// <param name="collectionName">Name of collections</param>
 /// <param name="filter">Filter conditions</param>
 /// <returns>First document or null</returns>
 public static async Task<BsonDocument> GetFirst(String collectionName, FilterDefinition<BsonDocument> filter)
 {
     List<BsonDocument> all = await GetAll(collectionName, filter);
     return all.FirstOrDefault();
 }
Ejemplo n.º 44
0
        public Task RemoveAsync(TKey id)
        {
            FilterDefinition <TEntity> filter = Builders <TEntity> .Filter.Eq("_id", id);

            return(Collection.DeleteOneAsync(filter));
        }
        private static async System.Threading.Tasks.Task <FilterDefinition <BsonDocument> > UpdateUser(SimpleMessage message, IMongoCollection <BsonDocument> col, FilterDefinition <BsonDocument> filtro, BsonDocument res, UserProfile user)
        {
            user.Contador = (Int32)res.GetValue("Contador") + 1;
            filtro        = await col.FindOneAndUpdateAsync(
                Builders <BsonDocument> .Filter.Eq("Id", message.Id),
                Builders <BsonDocument> .Update.Set("Contador", user.Contador)
                );

            return(filtro);
        }
Ejemplo n.º 46
0
        private static void Upsert(IMongoCollection<BsonDocument> collection, BsonDocument newDoc, FilterDefinition<BsonDocument> filter)
        {
            var options = new UpdateOptions();
            options.IsUpsert = true;

            collection.ReplaceOneAsync(filter, newDoc, options).Wait();
        }
 /// <summary>
 ///
 /// </summary>
 /// <typeparam name="T">文档类型</typeparam>
 /// <param name="collectionName">集合名称</param>
 /// <param name="session">会话句柄(作用于事务)</param>
 /// <param name="filter">过滤器</param>
 /// <param name="options">设置</param>
 /// <param name="cancellationToken">标记</param>
 /// <returns></returns>
 public long CountDocuments <T>(string collectionName, IClientSessionHandle session, FilterDefinition <T> filter, CountOptions options = null, CancellationToken cancellationToken = default) where T : BaseMongoEntity
 {
     return(Database.GetCollection <T>(collectionName).CountDocuments(session, filter, options, cancellationToken));
 }
Ejemplo n.º 48
0
 private List<Subscription> GetSubscriptions(FilterDefinition<BsonDocument> filter)
 {
     List<Subscription> result = new List<Subscription>();
     IMongoDatabase database = GetDatabase(DATABASE_NAME, false);
     IMongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>(COLLECTION_NAME);
     IAsyncCursor<BsonDocument> mongoCursor = collection.FindSync(filter);
     while (mongoCursor.MoveNext())
     {
         foreach (BsonDocument item in mongoCursor.Current)
         {
             result.Add(LoadSubscription(item));
         }
     }
     return result;
 }
Ejemplo n.º 49
0
        public async Task<List<string>> GetSkillNamesFromOffersMatchingQueryAsync(string queryToLower, FilterDefinition<Skill> skillFilterDefinition)
        {
            var filterFromOffers = Builders<JobOffer>.Filter.ElemMatch(offer => offer.Skills, skillFilterDefinition);
            var skillsFromOffers = await dbContext.JobOffers
                .Find(filterFromOffers)
                .Project(r => r.Skills.Where(s => s.NameToLower.StartsWith(queryToLower)))
                .ToListAsync();

            var skillNamesFromOffers = skillsFromOffers.SelectMany(r => r).Select(r => r.Name).ToList();
            return skillNamesFromOffers;
        }
Ejemplo n.º 50
0
        static async Task findDocuments(IMongoCollection<Person> collection, FilterDefinition<Person> searchFilter)
        {

            //Option 1: for iterting over many documents on the server.
            Console.WriteLine("--------------------------------------------------------------------");
            using (var cursor = await collection.Find(searchFilter).Skip(1).Limit(1).ToCursorAsync())
            {
                while (await cursor.MoveNextAsync())  //iterate over each batch
                {
                    foreach (var doc in cursor.Current)
                    {
                        Console.WriteLine("OPT 1:" + doc.ToBsonDocument().ToString());
                    }
                }
            }
            
            Console.WriteLine("--------------------------------------------------------------------");
            
            //Option 2: for listing documents on the server.
            var list = await collection.Find(x => x.Name == "jones" && x.Age <= 31).ToListAsync();
            foreach (var doc in list)
            {
                Console.WriteLine("OPT 2:" + doc.ToBsonDocument().ToString());
            }

            Console.WriteLine("--------------------------------------------------------------------");

            // Option 3: using the ForEachAsynch()  with a lambda function, projection, sort, and expression trees.
          
            await collection.Find(searchFilter)
                .Sort("{Age:-1}")
                .Project(Builders<Person>.Projection.Include(x => x.Name).Include(x=>x.Age).Exclude("_id"))
                .ForEachAsync(doc => Console.WriteLine("OPT 3:" + doc.ToBsonDocument().ToString()));

            //Option 4: Option 3 with a anonymous function to do a general calc client side.
            await collection.Find(searchFilter)
                .Sort("{Age:-1}")
                .Project((x => new {x.Name, CalcAge = x.Age + 20}))
                .ForEachAsync(doc => Console.WriteLine("OPT 4:" + doc.ToBsonDocument().ToString()));
        }
Ejemplo n.º 51
-1
        static async Task findDocuments(IMongoCollection<student> collection, FilterDefinition<student> searchFilter)
        {

            //Option 1: for iterting over many documents on the server.
            Console.WriteLine("--------------------------------------------------------------------");
            using (var cursor = await collection.Find(searchFilter)
                .Sort("{student_id:1, score:-1}")
                .ToCursorAsync())
            {
                int i = 1;
                using (StreamWriter w = File.AppendText("c:\\data\\test2.txt"))
                {
                    while (await cursor.MoveNextAsync())  //iterate over each batch
                    {
                        foreach (var doc in cursor.Current)
                        {
                            string text = i + " :=> sid: " + doc.student_id + ":" + doc.score;
                            Console.WriteLine(text);
                            w.WriteLine(text);
                            if (i % 4 == 0)
                            {
                                Console.WriteLine("lowest score for " + doc.student_id + " is " + doc.score);
                                w.WriteLine("lowest score for " + doc.student_id + " is " + doc.score);
                                await collection.DeleteOneAsync(a => a.Id == doc.Id);
                            }
                            i++;
                        }
                    }
                }
            }
        }