Ejemplo n.º 1
5
 public async Task WhenGet_Borough_Name_Returns_RestaurantList()
 {
     var collection = _database.GetCollection<BsonDocument>("restaurants");
     var builder = new FilterDefinitionBuilder<BsonDocument>();
     var filter = builder.Eq("borough", "Bronx");        
     var result = await collection.Find(filter).ToListAsync();
     Assert.AreEqual(2338, result.Count());
 }
Ejemplo n.º 2
4
        public async Task OneStepUpdate(int amount = 1000)
        {
            var filterDefinitionBuilder = new FilterDefinitionBuilder<Student>();
            var updateDefinitionBuilder = new UpdateDefinitionBuilder<Student>();
            for (var i = 0; i < amount; i++)
            {                
                await studentsCollection.UpdateOneAsync(
                    filterDefinitionBuilder.Eq<string>((Student x) => x.Id, $"Students/{i}"),
                    updateDefinitionBuilder.Inc<int>((Student x) => x.Age, 1));

            }            
        }
Ejemplo n.º 3
1
        public async Task WhenGet_Cuisine_Or_ZipCode_Returns_RestaurantList()
        {
            var collection = _database.GetCollection<BsonDocument>("restaurants");
            var builder = new FilterDefinitionBuilder<BsonDocument>();
            var filter = builder.Eq("cuisine", "Bakery") | builder.Eq("address.zipcode", "10462");

            var result = await collection.Find(filter).ToListAsync();
            Assert.AreEqual(834, result.Count());
        }
Ejemplo n.º 4
0
        public IEnumerable <BaseNode> GetBreadcrumbs(Guid itemId)
        {
            var filter = _filterBase & _builder.Eq("_id", itemId);

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

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

                return(result);
            }
            else
            {
                return(parents);
            }
        }
Ejemplo n.º 5
0
        public static FilterDefinition <MongoContentEntity> ToFilter(this Query query, Guid schemaId, Status[] status)
        {
            var filters = new List <FilterDefinition <MongoContentEntity> >
            {
                Filter.Eq(x => x.IndexedSchemaId, schemaId),
                Filter.Ne(x => x.IsDeleted, true)
            };

            if (status != null)
            {
                filters.Add(Filter.In(x => x.Status, status));
            }

            var filter = query.BuildFilter <MongoContentEntity>();

            if (filter.Filter != null)
            {
                if (filter.Last)
                {
                    filters.Add(filter.Filter);
                }
                else
                {
                    filters.Insert(0, filter.Filter);
                }
            }

            return(Filter.And(filters));
        }
        public async Task <IReadOnlyList <IConfigurationEntry> > GetEntries(string component, ConfigurationPath pathPrefix, bool forPages = false, bool recursive = true)
        {
            var filterBuilder = new FilterDefinitionBuilder <MongoDbConfigurationDocument>();

            if (string.IsNullOrWhiteSpace(component))
            {
                component = "root";
            }
            var filter = filterBuilder.Eq(a => a.Component, component);

            if (!ConfigurationPath.IsNullOrEmpty(pathPrefix))
            {
                filter = recursive ? filterBuilder.Regex(a => a.Path, new Regex(pathPrefix.ToString(asPrefix: true))) : filterBuilder.Eq(a => a.Path, pathPrefix.ToString());
            }
            if (forPages)
            {
                filter = filter & filterBuilder.Eq(a => a.VisibleToPages, true);
            }

            var results = await settingsCollectionData.FindAsync(filter);

            var records = await results.ToListAsync();

            return(records.Select(doc => RebuildConfigurationEntry(doc)).ToList());
        }
        private BsonDocument GetBsonFilter(Platforms platform, string platformKey = null)
        {
            var builder = new FilterDefinitionBuilder <BsonDocument>();
            var filter  = builder.Eq("Platform", platform.ToString()) & builder.Eq("Key", platformKey);

            return(filter.ToBsonDocument());
        }
Ejemplo n.º 8
0
        public async Task <Guid> DeleteItemAsync(Guid id)
        {
            var filter = filterBuilder.Eq(item => item.Id, id);
            await itemCollection.DeleteOneAsync(filter);

            return(id);
        }
        public void UserUpdateDoesNotWipeOutIgnoredFields()
        {
            if (!BsonClassMap.IsClassMapRegistered(typeof(Profile)))
            {
                BsonClassMap.RegisterClassMap <Profile>();
            }

            NameValueCollection config = new NameValueCollection();

            config.Add("connectionStringName", _connStrName);
            config.Add("applicationName", _applicationName);
            config.Add("requiresUniqueEmail", "false");
            config.Add("passwordFormat", "Clear");
            config.Add("enablePasswordRetrieval", "true");
            provider.Initialize(null, config);
            MembershipCreateStatus status;

            Membership.CreateUser("foo", "bar!bar", "*****@*****.**", "question", "answer", true, out status);

            // ensure user created correctly
            MembershipUser user = Membership.GetUser("foo");

            Assert.AreEqual("question", user.PasswordQuestion);


            // save Profile over User
            var mongoProvider = (MembershipProvider)Membership.Provider;
            var profiles      = mongoProvider.Database.GetCollection <Profile>(mongoProvider.CollectionName);

            var profile = profiles.AsQueryable().First(u => u.LowercaseUsername == "foo");

            profile.FirstName = "Neo";

            FilterDefinitionBuilder <Profile> fb = new FilterDefinitionBuilder <Profile>();

            profiles.ReplaceOne(fb.Eq(p => p.Id, profile.Id), profile);

            // ensure profile saved correctly
            profile = profiles.Find(fb.Eq(p => p.LowercaseUsername, "foo")).First();
            Assert.AreEqual("Neo", profile.FirstName);
            Assert.AreEqual("question", profile.PasswordQuestion);

            // validate User
            var valid = Membership.ValidateUser("foo", "bar!bar");

            Assert.AreEqual(true, valid);

            // ensure profile fields still in database
            profile = profiles.Find(fb.Eq(p => p.LowercaseUsername, "foo")).First();
            Assert.AreEqual("Neo", profile.FirstName);
            Assert.AreEqual("question", profile.PasswordQuestion);

            // update User
            user.ChangePassword("bar!bar", "foo!foo");

            // ensure profile fields still in database
            profile = profiles.Find(fb.Eq(p => p.LowercaseUsername, "foo")).First();
            Assert.AreEqual("Neo", profile.FirstName);
            Assert.AreEqual("question", profile.PasswordQuestion);
        }
Ejemplo n.º 10
0
        public void addOrUpdate(Person p)
        {
            //var filter = new BsonDocument();
            //filter.Add("firstname", p.FirstName);
            //filter.Add("lastname", p.LastName);

            //var newperson = new bsondocument();
            //newperson.add("firstname", p.firstname);
            //newperson.add("lastname", p.lastname);
            //if (p.phonenumber != null)
            //{
            //    newperson.add("phonenumber", p.phonenumber);
            //}

            var builder = new FilterDefinitionBuilder <Person>();
            var filter  = builder.Eq(x => x.FirstName, p.FirstName) & builder.Eq(x => x.LastName, p.LastName);

            if (collection.Find <Person>(filter).FirstOrDefault() != null)
            {
                collection.FindOneAndUpdate <Person>(
                    //Builders<Person>.Filter.Eq("FirstName", p.FirstName),
                    filter,
                    Builders <Person> .Update.Set("PhoneNumber", p.PhoneNumber)
                    );
            }
            else
            {
                collection.InsertOne(p);
            }

            collection = db.GetCollection <Person>("People");
        }
Ejemplo n.º 11
0
        private static void CreateOrderTypeFilter(HeatDataResultRequestDto input, FilterDefinitionBuilder <BsonDocument> builderFilter, List <FilterDefinition <BsonDocument> > filterDefinitions)
        {
            List <FilterDefinition <BsonDocument> > orderTypeFilterDefinitions = new List <FilterDefinition <BsonDocument> >();

            input.OrderType.ForEach(x =>
            {
                switch (x)
                {
                case InputOrderType.TotalOrder:
                default:
                    break;

                case InputOrderType.ImmediateOrder:
                    orderTypeFilterDefinitions.Add(builderFilter.Eq("orderType", OrderType.Immediate));
                    break;

                case InputOrderType.BookingOrder:
                    orderTypeFilterDefinitions.Add(builderFilter.And(builderFilter.Eq("orderType", OrderType.Booking), builderFilter.Eq("orderType2", BookingOrderType.Normal)));
                    break;

                case InputOrderType.PickupOrder:
                    orderTypeFilterDefinitions.Add(builderFilter.Eq("orderType2", BookingOrderType.Pickup));
                    break;

                case InputOrderType.DropoffOrder:
                    orderTypeFilterDefinitions.Add(builderFilter.Eq("orderType2", BookingOrderType.Dropoff));
                    break;
                }
            });
            if (orderTypeFilterDefinitions.Count > 0)
            {
                filterDefinitions.Add(builderFilter.Or(orderTypeFilterDefinitions));
            }
        }
Ejemplo n.º 12
0
        public async System.Threading.Tasks.Task <bool> IsUnique(string login, long?id = null, long?teamId = null, string?teamName = null)
        {
            var filterBuilder = new FilterDefinitionBuilder <User>();
            var filter        = filterBuilder.Empty;

            if (!String.IsNullOrWhiteSpace(login))
            {
                filter = filter & filterBuilder.Eq("login", login);
            }

            if (id != null)
            {
                filter = filter & filterBuilder.Not(filterBuilder.Eq("id", id.Value));
            }

            if (teamId != null)
            {
                filter = filter & filterBuilder.Eq("teamId", teamId.Value);
            }

            if (!String.IsNullOrWhiteSpace(teamName))
            {
                filter = filter & filterBuilder.Eq("teamName", teamName);
            }

            var foundUsersList = await Users.Find(filter).ToListAsync();

            return(foundUsersList.Count == 0);
        }
        /// <summary>
        /// Find
        /// </summary>
        /// <param name="requestFilter"></param>
        /// <returns></returns>
        public async Task <IEnumerable <ArticleContent> > Find(ConditionFilter requestFilter)
        {
            var skip             = 0;
            var take             = 10;
            var filterDefinition = new FilterDefinitionBuilder <ArticleContent>();

            var filter = filterDefinition.Eq(x => x.ContentType, requestFilter.ContentType);

            if (!requestFilter.Brand.IsNullOrEmpty())
            {
                filter = filter & filterDefinition.Where(x => x.Brand.Contains(requestFilter.Brand));
            }
            if (!requestFilter.Category.IsNullOrEmpty())
            {
                filter = filter & filterDefinition.Eq(x => x.Category.Parent, requestFilter.Category);
            }
            if (!requestFilter.Language.IsNullOrEmpty())
            {
                filter = filter & filterDefinition.Eq(x => x.Market, requestFilter.Language);
            }

            skip = take * (requestFilter.Page - 1);


            return(await _repository.FindAsync <ArticleContent>(filter, orderBy : x => x.GetOrderFor(requestFilter.Ordering), skip : skip, take : take));
        }
Ejemplo n.º 14
0
        /// <summary>
        ///  Attempts, for the specified amount of time, to acquire an exclusive lock
        /// </summary>
        /// <param name="lifetime">A TimeSpan representing the amount of time after which the lock is automatically released</param>
        /// <param name="timeout">A TimeSpan representing the amount of time to wait for the lock</param>
        /// <returns></returns>
        public async Task <IAcquire> AcquireAsync(TimeSpan lifetime, TimeSpan timeout)
        {
            if (lifetime < TimeSpan.Zero || lifetime > TimeSpan.MaxValue)
            {
                throw new ArgumentOutOfRangeException(nameof(lifetime), "The value of lifetime in milliseconds is negative or is greater than MaxValue");
            }
            if (timeout < TimeSpan.Zero || timeout > TimeSpan.MaxValue)
            {
                throw new ArgumentOutOfRangeException(nameof(timeout), "The value of timeout in milliseconds is negative or is greater than MaxValue");
            }

            Guid acquireId = Guid.NewGuid();

            while (await TryUpdate(lifetime, acquireId) == false)
            {
                using (IAsyncCursor <LockAcquire <T> > cursor = await _locks.FindAsync(_builder.Eq(x => x.Id, _id)))
                {
                    LockAcquire <T> acquire = await cursor.FirstOrDefaultAsync();

                    if (acquire != null && await WaitSignal(acquire.AcquireId, timeout) == false)
                    {
                        return(await TryUpdate(lifetime, acquireId) == false ? new AcquireResult() : new AcquireResult(acquireId));
                    }
                }
            }

            return(new AcquireResult(acquireId));
        }
Ejemplo n.º 15
0
        public static FilterDefinition <MongoAssetEntity> BuildFilter(this ClrQuery query, Guid appId)
        {
            var filters = new List <FilterDefinition <MongoAssetEntity> >
            {
                Filter.Eq(x => x.IndexedAppId, appId),
                Filter.Eq(x => x.IsDeleted, false)
            };

            var filter = query.BuildFilter <MongoAssetEntity>(false);

            if (filter.Filter != null)
            {
                if (filter.Last)
                {
                    filters.Add(filter.Filter);
                }
                else
                {
                    filters.Insert(0, filter.Filter);
                }
            }

            if (filters.Count > 1)
            {
                return(Filter.And(filters));
            }
            else if (filters.Count == 1)
            {
                return(filters[0]);
            }
            else
            {
                return(new BsonDocument());
            }
        }
        private List <FilterDefinition <Flight> > CreateClauses(SearchCriteriaModel criteriaModel, FilterDefinitionBuilder <Flight> filterBuilder)
        {
            var clauses = new List <FilterDefinition <Flight> >();

            if (criteriaModel.FromDate != null)
            {
                var fromDate = DateTime.SpecifyKind(DateTime.Parse(criteriaModel.FromDate), DateTimeKind.Utc);
                var clause   = filterBuilder.Gte(f => f.FlightDate, fromDate);
                clauses.Add(clause);
            }
            if (criteriaModel.ToDate != null)
            {
                var toDate = DateTime.SpecifyKind(DateTime.Parse(criteriaModel.ToDate), DateTimeKind.Utc);
                var clause = filterBuilder.Lte(f => f.FlightDate, toDate);
                clauses.Add(clause);
            }
            if (criteriaModel.AirlineId != null)
            {
                var clause = filterBuilder.Eq(f => f.AirlineId, criteriaModel.AirlineId.Value);
                clauses.Add(clause);
            }
            if (criteriaModel.OriginId != null)
            {
                var clause = filterBuilder.Eq(f => f.OriginAirportId, criteriaModel.OriginId.Value);
                clauses.Add(clause);
            }
            if (criteriaModel.DestinationId != null)
            {
                var clause = filterBuilder.Eq(f => f.DestinationAirportId, criteriaModel.DestinationId.Value);
                clauses.Add(clause);
            }
            return(clauses);
        }
Ejemplo n.º 17
0
        public async virtual Task <PaymentReadModel> GetPaymentDetailsAsync(Guid aggregateId, Guid userId)
        {
            FilterDefinitionBuilder <PaymentReadModel> builder = Builders <PaymentReadModel> .Filter;
            var filter = builder.Eq(p => p.Id, aggregateId) & builder.Eq(p => p.UserId, userId);

            return(await _paymentsRead.Find(filter).FirstAsync());
        }
Ejemplo n.º 18
0
        async Task <bool> IPersist.ToggleMarkAllAsync(string q, PersistedMessageStatusOptions newMark, PersistedMessageStatusOptions oldMark, CancellationToken token)
        {
            if (this.serviceDown)
            {
                throw new ServiceEndpointDownException("Mongo Persist Service is Down");
            }

            IMongoCollection <PersistedMessage> collection = this.GetCollection();



            try {
                token.ThrowIfCancellationRequested();
                FilterDefinitionBuilder <PersistedMessage> fBuilder = Builders <PersistedMessage> .Filter;

                var qfilter = fBuilder.And(fBuilder.Eq(g => g.Status, oldMark), fBuilder.Eq(g => g.Queue, q));
                var update  = Builders <PersistedMessage> .Update.Set(g => g.Status, newMark);

                await collection.UpdateManyAsync(qfilter, update, null, token);

                return(true);
            } catch (Exception e) {
                this.serviceDown = true;
                throw new ServiceEndpointDownException("Mongo Persist Service is Down", e);
            }
        }
Ejemplo n.º 19
0
        public static FilterDefinition <NetstatDocument> GetNetstatForWorker(string worker)
        {
            // netstat-info.txt used by Windows and netstat-anp.txt used by Linux
            var fileSubQuery = Query.Eq("file", "netstat-info.txt") | Query.Eq("file", "netstat-anp.txt");

            return(Query.Eq("worker", worker) & fileSubQuery);
        }
Ejemplo n.º 20
0
        private async void PublishHits(object state)
        {
            var hasHit = _queue.TryTake(out var hit);

            do
            {
                if (_stoppingCancellationToken.IsCancellationRequested)
                {
                    return;
                }

                var filterBuilder = new FilterDefinitionBuilder <BsonDocument>();
                var filter        = filterBuilder.And(
                    filterBuilder.Eq("name", hit.Name),
                    filterBuilder.Eq("size", hit.Size)
                    );

                var updateBuilder = new UpdateDefinitionBuilder <BsonDocument>();
                var update        = updateBuilder
                                    .Inc("hits", 1)
                                    .Set("last-hit", DateTime.UtcNow);

                await _collection.UpdateOneAsync(
                    filter,
                    update,
                    new UpdateOptions { IsUpsert = true },
                    _stoppingCancellationToken.Token);
            } while((hasHit = _queue.TryTake(out hit)));
        }
Ejemplo n.º 21
0
        public static FilterDefinition <MongoContentEntity> BuildQuery(ODataUriParser query, Guid schemaId, Schema schema, Status[] status)
        {
            var filters = new List <FilterDefinition <MongoContentEntity> >
            {
                Filter.Eq(x => x.SchemaId, schemaId),
                Filter.Eq(x => x.IsLatest, true),
                Filter.In(x => x.Status, status)
            };

            var filter = FilterBuilder.Build(query, schema);

            if (filter != null)
            {
                filters.Add(filter);
            }

            if (filters.Count > 1)
            {
                return(Filter.And(filters));
            }
            else if (filters.Count == 1)
            {
                return(filters[0]);
            }
            else
            {
                return(new BsonDocument());
            }
        }
Ejemplo n.º 22
0
        public IUser Get(string userId)
        {
            var search = _filter.Eq("UserId", userId);
            var user   = collection.Find(search).FirstOrDefault();

            return(user);
        }
Ejemplo n.º 23
0
        public void And()
        {
            var fb = new FilterDefinitionBuilder <BasicDocument>();

            Find(fb.And(fb.Eq(x => x.Id, _item.Id), fb.Eq(x => x.Name, _item.Name)))
            .ShouldHaveOneResultMatching(_item);
        }
Ejemplo n.º 24
0
        public static FilterDefinition <MongoContentEntity> BuildQuery(ODataUriParser query, Guid schemaId, Status[] status, PropertyCalculator propertyCalculator)
        {
            var filters = new List <FilterDefinition <MongoContentEntity> >
            {
                Filter.Eq(x => x.SchemaId, schemaId),
                Filter.In(x => x.Status, status),
                Filter.Eq(x => x.IsDeleted, false)
            };

            var filter = query.BuildFilter <MongoContentEntity>(propertyCalculator);

            if (filter.Filter != null)
            {
                if (filter.Last)
                {
                    filters.Add(filter.Filter);
                }
                else
                {
                    filters.Insert(0, filter.Filter);
                }
            }

            if (filters.Count == 1)
            {
                return(filters[0]);
            }
            else
            {
                return(Filter.And(filters));
            }
        }
Ejemplo n.º 25
0
        public async System.Threading.Tasks.Task <List <User> > GetUsers(
            long?id,
            DateTime?date,
            string?teamName
            )
        {
            var filterBuilder = new FilterDefinitionBuilder <User>();
            var filter        = filterBuilder.Empty;

            if (id.HasValue)
            {
                filter = filter & filterBuilder.Eq("id", id.Value);
            }

            if (date.HasValue)
            {
                filter = filter & filterBuilder.Eq("date", date.ToString());
            }

            if (!String.IsNullOrWhiteSpace(teamName))
            {
                filter = filter & filterBuilder.Eq("teamName", teamName);
            }

            return(await Users.Find(filter).ToListAsync());
        }
Ejemplo n.º 26
0
        public static FilterDefinition <MongoAssetEntity> BuildQuery(ODataUriParser query, Guid appId)
        {
            var filters = new List <FilterDefinition <MongoAssetEntity> >
            {
                Filter.Eq(x => x.AppIdId, appId),
                Filter.Eq(x => x.IsDeleted, false)
            };

            var filter = query.BuildFilter <MongoAssetEntity>(PropertyCalculator, false);

            if (filter.Filter != null)
            {
                if (filter.Last)
                {
                    filters.Add(filter.Filter);
                }
                else
                {
                    filters.Insert(0, filter.Filter);
                }
            }

            if (filters.Count > 1)
            {
                return(Filter.And(filters));
            }
            else if (filters.Count == 1)
            {
                return(filters[0]);
            }
            else
            {
                return(new BsonDocument());
            }
        }
Ejemplo n.º 27
0
        private FilterDefinition <ToDoListEntity> ApplyWhereStatement(FilterDefinitionBuilder <ToDoListEntity> builder, ListQueryDataStructure queryDataStructure)
        {
            FilterDefinition <ToDoListEntity> filter = builder.Ne(x => x.Status, (int)ToDoListStatus.Archived);

            if (queryDataStructure.Id.HasValue)
            {
                filter = filter & (builder.Eq(x => x.Id, queryDataStructure.Id.Value));
            }

            if (queryDataStructure.UserId.HasValue)
            {
                filter = filter & (builder.Eq(x => x.UserId, queryDataStructure.UserId.Value));
            }

            if (!string.IsNullOrWhiteSpace(queryDataStructure.Name))
            {
                filter = filter & (builder.Regex(x => x.Name, queryDataStructure.Name));
            }

            if (queryDataStructure.Statuses != null && queryDataStructure.Statuses.Any())
            {
                filter = filter & (builder.In(x => x.Status, queryDataStructure.Statuses));
            }

            return(filter);
        }
Ejemplo n.º 28
0
        public async IAsyncEnumerable <Bill> GetAsync(string personId, int?month)
        {
            FilterDefinitionBuilder <Bill> builder = Builders <Bill> .Filter;
            FilterDefinition <Bill>        filter  = FilterDefinition <Bill> .Empty;
            Bill bill;

            if (!String.IsNullOrEmpty(personId))
            {
                filter &= builder.Eq(nameof(bill.PersonId), personId);
            }

            if (month.HasValue)
            {
                filter &= builder.Eq(nameof(bill.DueMonth), month);
            }

            using (IAsyncCursor <Bill> cursor = await _bills.FindAsync(filter))
            {
                while (await cursor.MoveNextAsync())
                {
                    foreach (Bill currentBill in cursor.Current)
                    {
                        yield return(currentBill);
                    }
                }
            }
        }
        public async Task <bool> DeleteAsync(Guid id)
        {
            var filter = filterBuilder.Eq(item => item.Id, id);
            var result = await itemsCollection.DeleteOneAsync(filter);

            return(result.DeletedCount > 0);
        }
        public async Task <long> CountByPlayerIdAsync(int id)
        {
            FilterDefinitionBuilder <Game> filterBuilder = Builders <Game> .Filter;
            FilterDefinition <Game>        whiteEq       = filterBuilder.Eq("white.userId", id);
            FilterDefinition <Game>        blackEq       = filterBuilder.Eq("black.userId", id);

            return(await gameCollection.CountAsync(filterBuilder.Or(whiteEq, blackEq)));
        }
Ejemplo n.º 31
0
        /// <summary>
        /// 透過帳號密碼取得使用者資訊
        /// </summary>
        /// <param name="UID"></param>
        /// <param name="UserPwd"></param>
        /// <returns></returns>
        public UserModel GetUser(string UID, string UserPwd)
        {
            FilterDefinitionBuilder <UserModel> filter = Builders <UserModel> .Filter;

            FilterDefinition <UserModel> filters = filter.Eq("UID", UID) & filter.Eq("UserPwd", UserPwd);

            return(mongoContext.QueryOne <UserModel>(filters));
        }
Ejemplo n.º 32
0
        public async Task DeleteExpenseAsync(Guid id)
        {
            //Finds the expense to replace
            var filter = filterBuilder.Eq(expenseToDelete => expenseToDelete.Id, id);

            //Deletes the expense we found
            await expensesCollection.DeleteOneAsync(filter);
        }
Ejemplo n.º 33
0
        public long CountByPlayerId(int id)
        {
            FilterDefinitionBuilder <Game> filterBuilder = Builders <Game> .Filter;
            FilterDefinition <Game>        whiteEq       = filterBuilder.Eq("white.userId", id);
            FilterDefinition <Game>        blackEq       = filterBuilder.Eq("black.userId", id);

            return(gameCollection.Count(filterBuilder.Or(whiteEq, blackEq)));
        }
Ejemplo n.º 34
0
        public async Task Update_Multiple_Restaurants()
        {
            var collection = _database.GetCollection<BsonDocument>("restaurants");
            var builder = new FilterDefinitionBuilder<BsonDocument>();
            var filter = builder.Eq("address.zipcode", "10462") & builder.Eq("cuisine", "Other");         
            var update = Builders<BsonDocument>.Update
                .Set("cuisine", "Category TBD")                
                .CurrentDate("lastModified");
            var result = await collection.UpdateOneAsync(filter, update);

            Assert.AreEqual(1, result.MatchedCount);

            if (result.IsModifiedCountAvailable)
            {
                Assert.AreEqual(1, result.ModifiedCount);
            }
        }
Ejemplo n.º 35
0
 public async Task WhenGet_Grade_Letter_Returns_RestaurantList()
 {
     var collection = _database.GetCollection<BsonDocument>("restaurants");
     var builder = new FilterDefinitionBuilder<BsonDocument>();
     var filter = builder.Eq("grades.grade", "A");
     var result = await collection.Find(filter).ToListAsync();
     Assert.AreEqual(23440, result.Count());
 }
Ejemplo n.º 36
0
 public async Task OneStepDelete(int amount = 1000)
 {
     var filterDefinitionBuilder = new FilterDefinitionBuilder<Student>();
     
     for (var i = 0; i < amount; i++)
     {
         var filter = filterDefinitionBuilder.Eq((Student x) => x.Id, $"Students/{i}");
         await studentsCollection.DeleteOneAsync(filter);                
     }
 }        
Ejemplo n.º 37
0
 public async Task TwoStepUpdate(int amount =1000)
 {
     var filterDefinitionBuilder = new FilterDefinitionBuilder<Student>();
     
     for (var i = 0; i < amount; i++)
     {
         var foundStudent = await studentsCollection.Find<Student>((Student x) => x.Id == $"Students/{i}").FirstAsync();                
         foundStudent.Age++;
         await studentsCollection.ReplaceOneAsync(filterDefinitionBuilder.Eq<string>((Student x) => foundStudent.Id, foundStudent.Id), foundStudent);
     }
 }
 private List<FilterDefinition<Flight>> CreateClauses(SearchCriteriaModel criteriaModel, FilterDefinitionBuilder<Flight> filterBuilder)
 {
     var clauses = new List<FilterDefinition<Flight>>();
     if (criteriaModel.FromDate != null)
     {
         var fromDate = DateTime.SpecifyKind(DateTime.Parse(criteriaModel.FromDate), DateTimeKind.Utc);
         var clause = filterBuilder.Gte(f => f.FlightDate, fromDate);
         clauses.Add(clause);
     }
     if (criteriaModel.ToDate != null)
     {
         var toDate = DateTime.SpecifyKind(DateTime.Parse(criteriaModel.ToDate), DateTimeKind.Utc);
         var clause = filterBuilder.Lte(f => f.FlightDate, toDate);
         clauses.Add(clause);
     }
     if (criteriaModel.AirlineId != null)
     {
         var clause = filterBuilder.Eq(f => f.AirlineId, criteriaModel.AirlineId.Value);
         clauses.Add(clause);
     }
     if (criteriaModel.OriginId != null)
     {
         var clause = filterBuilder.Eq(f => f.OriginAirportId, criteriaModel.OriginId.Value);
         clauses.Add(clause);
     }
     if (criteriaModel.DestinationId != null)
     {
         var clause = filterBuilder.Eq(f => f.DestinationAirportId, criteriaModel.DestinationId.Value);
         clauses.Add(clause);
     }
     return clauses;
 }