コード例 #1
0
ファイル: BaseRepo.cs プロジェクト: tuankha1994/KhV
        public async Task DeleteManyAsync(FilterDefinition <TEntity> filter)
        {
            var deliveryManyAsync = DbSet?.DeleteManyAsync(filter);

            if (deliveryManyAsync != null)
            {
                await deliveryManyAsync;
            }
        }
コード例 #2
0
        public async Task <IActionResult> Save(List <NetworkNode> nodes)
        {
            foreach (var item in nodes)
            {
                if (item.Id == null)
                {
                    await nodesCol.InsertOneAsync(item);
                }
                else
                {
                    await nodesCol.ReplaceOneAsync(n => n.Id == item.Id, item);
                }
            }
            var ids = nodes.Select(n => n.Id);
            await nodesCol.DeleteManyAsync(n => !ids.Contains(n.Id));

            return(Ok());
        }
コード例 #3
0
        public virtual async Task <bool> DeleteManyAsync(IEnumerable <T> models,
                                                         CancellationToken?cancellationToken = null)
        {
            if (models == null)
            {
                throw new ArgumentNullException(nameof(models));
            }

            var ids    = models.Select(m => m.Id);
            var filter = new ExpressionFilterDefinition <T>(
                doc => ids.Contains(doc.Id));

            var result = await collection.DeleteManyAsync(
                filter : filter,
                cancellationToken : cancellationToken.GetValueOrDefault());

            return(result.DeletedCount == models.Count());
        }
コード例 #4
0
        protected override Task DeleteMessagesToAsync(string persistenceId, long toSequenceNr, bool isPermanent)
        {
            var builder = Builders <JournalEntry> .Filter;
            var filter  = builder.Eq(x => x.PersistenceId, persistenceId);
            var update  = Builders <JournalEntry> .Update.Set(x => x.IsDeleted, true);

            if (toSequenceNr != long.MaxValue)
            {
                filter &= builder.Lte(x => x.SequenceNr, toSequenceNr);
            }

            if (isPermanent)
            {
                return(_collection.DeleteManyAsync(filter));
            }

            return(_collection.UpdateManyAsync(filter, update));
        }
コード例 #5
0
        /*
         * Remove All Documents (See https://docs.mongodb.com/getting-started/csharp/remove/)
         *
         * To remove all documents from a collection, pass an empty conditions document to the DeleteManyAsync method.
         *
         * var collection = _database.GetCollection<BsonDocument>("restaurants");
         * var filter = new BsonDocument();
         * var result = await collection.DeleteManyAsync(filter);
         */
        public virtual bool RemoveAll()
        {
            try
            {
                //var result = m_Entities.RemoveAll();
                //return result.DocumentsAffected == 1;

                var filter = new BsonDocument();
                var result = m_Entities.DeleteManyAsync(filter);

                return(result.IsCompleted);
            }
            catch
            {
            }

            return(false);
        }
コード例 #6
0
        public async Task <bool> DeleteAllByTaskBoardIdAsync(string taskBoardId, CancellationToken cancellationToken)
        {
            if (taskBoardId == null)
            {
                throw new ArgumentNullException(nameof(taskBoardId));
            }

            var mongoTaskBoardId = ObjectId.Parse(taskBoardId);

            var result = await _listsCollection.DeleteManyAsync(x => x.BoardId == mongoTaskBoardId, cancellationToken).ConfigureAwait(false);

            if (result.DeletedCount > 0)
            {
                return(true);
            }

            return(false);
        }
コード例 #7
0
        void run(double latMin, double lngMin, double size, IMongoCollection <BsonDocument> collection, IMongoCollection <BsonDocument> searchCollection)
        {
            //Console.Write("("+latMin+","+lngMin+")");
            int    nearbyCount;
            string json = "";

            //test for previous search
            //			Task<long> previousCount = searchCollection.Find(filter).CountAsync();
            //			previousCount.Wait();
            //Console.Write(previousCount.Result);
            Search s = previousSearch(latMin, lngMin, size);



            //new download
            if (s.count < 0 || s == null)
            {
                var builder = Builders <BsonDocument> .Filter;
                FilterDefinition <BsonDocument> filter = builder.Eq("size", size) & builder.Eq("lng", lngMin) & builder.Eq("lat", latMin);
                FilterDefinition <BsonDocument> delete = filter & builder.Lt("count", 0);
                searchCollection.DeleteManyAsync(delete);


                nearbyCount = download(json, latMin, lngMin, size, collection, searchCollection);
            }
            else
            {
                nearbyCount = s.count;
            }

            //recursive at smaller scale
            if ((nearbyCount >= 900) && (size > sizeMin))
            {
                double size01 = size / factor;
                for (int i = 0; i < factor; i++)
                {
                    for (int j = 0; j < factor; j++)
                    {
                        run((latMin + (size01 * i)), (lngMin + (size01 * j)), size01, collection, searchCollection);
                    }
                }
            }
        }
コード例 #8
0
ファイル: FormService.cs プロジェクト: Rud156/Forms
        public async Task <long> DeleteFormsCreatedBy(string createdBy)
        {
            var formTask = await formCollection.FindAsync(_ => _.createdBy == createdBy);

            List <FormViewModel> forms = await formTask.ToListAsync();

            HashSet <ObjectId> formObjectIds = new HashSet <ObjectId>(forms.Select(_ => _.Id));

            DeleteResult formDeleteResult = await formCollection.DeleteManyAsync(_ => _.createdBy == createdBy);

            if (!formDeleteResult.IsAcknowledged)
            {
                throw new Exception($"Unable to delete forms created by {createdBy}");
            }

            await fieldCollection.DeleteManyAsync(_ => formObjectIds.Contains(_.formId));

            return(formDeleteResult.DeletedCount);
        }
コード例 #9
0
 public void ClearCollection <CollectionType>(string collectionName)
 {
     if (collectionName.ToLower() == "all")
     {
         _shipC.DeleteManyAsync(new BsonDocument());
         _playerC.DeleteManyAsync(new BsonDocument());
         _accountC.DeleteManyAsync(new BsonDocument());
         _areaC.DeleteManyAsync(new BsonDocument());
         _shipStatsC.DeleteManyAsync(new BsonDocument());
         _layoutC.DeleteManyAsync(new BsonDocument());
         _teamC.DeleteManyAsync(new BsonDocument());
         _shipStatsC.DeleteManyAsync(new BsonDocument());
         _structureC.DeleteManyAsync(new BsonDocument());
     }
     if (CollectionExistsAsync(collectionName).Result)
     {
         mongoDatabase.GetCollection <CollectionType>(collectionName).DeleteManyAsync(new BsonDocument());
     }
 }
コード例 #10
0
        public async Task <IActionResult> Rebuild()
        {
            await _autocompleteCollection.DeleteManyAsync(_ => true);

            var houses = _houseCollection.AsQueryable();

            foreach (var house in houses)
            {
                var houseAutocompleteDto = new HouseAutocompleteDto();

                houseAutocompleteDto.HouseId           = house.MongoId;
                houseAutocompleteDto.Address           = house.address;
                houseAutocompleteDto.NormalizedAddress = NormalizeAddress(house.address);

                await _autocompleteCollection.InsertOneAsync(houseAutocompleteDto);
            }

            return(Ok());
        }
コード例 #11
0
        public virtual async Task <bool> SaveAllAsync(IEnumerable <TEntity> entities)
        {
            var result = await Collection.DeleteManyAsync(Builders <TEntity> .Filter.Empty);

            await Collection.InsertManyAsync(entities,
                                             new InsertManyOptions { BypassDocumentValidation = true, IsOrdered = false });

            //var chunkSize = 20;
            //foreach (var g in entities
            //    .Select((x, i) => new { Index = i, Value = x })
            //    .GroupBy(x => x.Index / chunkSize)
            //    .Select(x => x.Select(v => v.Value)))
            //{
            //    await Collection.InsertManyAsync(entities,
            //        new InsertManyOptions { BypassDocumentValidation = true, IsOrdered = false });
            //    await Task.Delay(1000);
            //}

            return(result.IsAcknowledged);
        }
コード例 #12
0
ファイル: Program.cs プロジェクト: ksjoberg/dd-trace-dotnet
        public static async Task RunAsync(IMongoCollection <BsonDocument> collection, BsonDocument newDocument)
        {
            var allFilter = new BsonDocument();

            using (var asyncScope = Tracer.Instance.StartActive("async-calls", serviceName: "Samples.MongoDB"))
            {
                await collection.DeleteManyAsync(allFilter);

                await collection.InsertOneAsync(newDocument);

                var count = await collection.CountDocumentsAsync(new BsonDocument());

                Console.WriteLine($"Documents: {count}");

                var find = await collection.FindAsync(allFilter);

                var allDocuments = await find.ToListAsync();

                Console.WriteLine(allDocuments.FirstOrDefault());
            }
        }
コード例 #13
0
        internal static DeleteResult DeleteSessionDocument(
            this MongoSessionStateStore obj,
            IMongoCollection <BsonDocument> sessionCollection,
            FilterDefinition <BsonDocument> query)
        {
            int attempts = 0;

            while (true)
            {
                try
                {
                    var task = sessionCollection.DeleteManyAsync(query);
                    task.Wait();

                    return(task.Result);
                }
                catch (Exception e)
                {
                    PauseOrThrow(ref attempts, obj, sessionCollection, e);
                }
            }
        }
コード例 #14
0
        public async Task RemoveAsync(IEnumerable <StellarisMod> mods, CancellationToken cancellationToken = default)
        {
            await _lock.WaitAsync(cancellationToken).ConfigureAwait(false);

            try
            {
                _log.LogDebug("Removing {Count} Stellaris mods from the database", mods.Count());
                IEnumerable <ObjectId>          ids    = mods.Select(e => e.ID);
                FilterDefinition <StellarisMod> filter = Builders <StellarisMod> .Filter.In(e => e.ID, ids);

                await _collection.DeleteManyAsync(filter, cancellationToken).ConfigureAwait(false);

                if (_cachingOptions.CurrentValue.Enabled)
                {
                    _stellarisModsCache.RemoveWhere(e => ids.Contains(e.Entity.ID));
                }
            }
            finally
            {
                _lock.Release();
            }
        }
コード例 #15
0
ファイル: ApiHelper.cs プロジェクト: majkii2115/RazjoAPI
        public async Task <bool> DeleteFamily(string userId, string familyId)
        {
            if (await ReturnUserRole(userId) == "PSY")
            {
                var family = await _familes.Find <Family>(x => x.Id == familyId).FirstOrDefaultAsync();

                if (family.USRId != userId && family.PSYId != userId)
                {
                    return(false);
                }

                var psy = await _users.Find <User>(x => x.Id == userId).FirstOrDefaultAsync();

                if (family.USRId != null)
                {
                    var usr = await _users.Find <User>(x => x.Id == family.USRId).FirstOrDefaultAsync();

                    usr.FamilyId.Remove(family.Id);
                    await _users.FindOneAndReplaceAsync(x => x.Id == usr.Id, usr);
                }

                psy.FamilyId.Remove(family.Id);

                await _calendarNotes.DeleteManyAsync(x => x.FamilyId == family.Id);

                await _visits.DeleteManyAsync(x => x.FamilyId == family.Id);

                await _familes.DeleteOneAsync(x => x.Id == familyId);

                await _users.FindOneAndReplaceAsync(x => x.Id == userId, psy);

                return(true);
            }
            else
            {
                return(false);
            }
        }
コード例 #16
0
        /// <summary>
        /// 根据匹配条件删除文档(异步)
        /// </summary>
        /// <param name="Match"></param>
        /// <returns></returns>
        public async Task <bool> DeleteManyAsync(FilterDefinition <T> Match)
        {
            IMongoCollection <T> cls = GetMongoCols();

            if (null == cls)
            {
                return(await Task.FromResult(false));
            }

            Task <DeleteResult> rlt = cls.DeleteManyAsync(Match);

            if (null == rlt)
            {
                return(await Task.FromResult(false));
            }

            if (rlt.Result.DeletedCount > 0)
            {
                return(await Task.FromResult(false));
            }

            return(await Task.FromResult(true));
        }
コード例 #17
0
        private async static Task DeleteFamilies(IMongoCollection <Family> collection)
        {
            try
            {
                Console.WriteLine("Deleting Andersen Family");
                var filter = Builders <Family> .Filter.Eq(family => family.LastName, "Andersen");

                var familyDeleteResult = await collection.DeleteManyAsync(filter);

                if (familyDeleteResult.DeletedCount == 1)
                {
                    Console.WriteLine($"Anderson Family deleted");
                }
            }
            catch (MongoCommandException ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                Console.WriteLine("Done !!!");
            }
        }
コード例 #18
0
        public async Task DeleteManyTheatersAsync()
        {
            /* By now, you probably have a good guess about how to use the driver
             * to delete multiple documents. If you'd like, stop the video
             * here and give it a try. Otherwise, let's take a look at how
             * we do it. First, we'll create the find filter:
             */

            var filter = Builders <Theater> .Filter.Eq(t => t.Location.Address.City, "Movieville");

            // And then we call the DeleteMany or DeleteManyAsync method:

            var result = await _theatersCollection.DeleteManyAsync(filter);

            Assert.AreEqual(3, result.DeletedCount);

            /* And that's it for Deletes! If you want to see one more example,
             * take look at the Cleanup method below. It removes all of the
             * test documents that were creted at the start of this unit test.
             * It uses the "Gte" ("Greater than or equal to") filter to
             * match the theaters we added, and deletes all of them in a
             * single line of code.
             */
        }
コード例 #19
0
        /// <summary>
        /// Delete user-related docs from various collections.
        /// </summary>
        public async Task DeleteUserAsync(string userId)
        {
            if (string.IsNullOrEmpty(userId))
            {
                throw new ArgumentException("", nameof(userId));
            }

            RealtimeOptions                 options = _realtimeOptions.Value;
            IEnumerable <DocConfig>         collectionsToProcess = options.UserDataDocs.Append(options.UserDoc);
            FilterDefinition <BsonDocument> idFilter             = Builders <BsonDocument> .Filter.Regex("_id", $"{userId}$");

            FilterDefinition <BsonDocument> dFilter = Builders <BsonDocument> .Filter.Regex("d", $"{userId}$");

            foreach (var collection in collectionsToProcess)
            {
                IMongoCollection <BsonDocument> snapshotCollection = _database.GetCollection <BsonDocument>(
                    collection.CollectionName);
                await snapshotCollection.DeleteManyAsync(idFilter);

                IMongoCollection <BsonDocument> opsCollection = _database.GetCollection <BsonDocument>(
                    $"o_{collection.CollectionName}");
                await opsCollection.DeleteManyAsync(dFilter);
            }
        }
コード例 #20
0
        public async Task Process()
        {
            var cursor = await _outboxMessages.Find(Builders <OutboxMessage> .Filter.Where(d => !d.Processed.HasValue)).ToCursorAsync();

            var publishedMessageIds = new List <Guid>();

            try
            {
                foreach (var message in cursor.ToEnumerable())
                {
                    await _eventListener.Publish(message.Data, message.Type);

                    publishedMessageIds.Add(message.Id);
                    await _outboxMessages.UpdateOneAsync(Builders <OutboxMessage> .Filter.Eq(d => d.Id, message.Id), Builders <OutboxMessage> .Update.Set(x => x.Processed, DateTime.UtcNow));
                }
            }
            finally
            {
                if (_outboxOptions.DeleteAfter)
                {
                    await _outboxMessages.DeleteManyAsync(Builders <OutboxMessage> .Filter.In(d => d.Id, publishedMessageIds));
                }
            }
        }
コード例 #21
0
 /// <summary>
 /// Deletes all locks for a user
 /// </summary>
 /// <param name="userId">Id of the user</param>
 /// <returns>Task</returns>
 public async Task DeleteAllLocksOfUser(string userId)
 {
     await _LockCollection.DeleteManyAsync(l => l.UserId == userId);
 }
コード例 #22
0
ファイル: Api.cs プロジェクト: kay-kim/mongo-csharp-driver
 private Task ClearData(IMongoCollection<BsonDocument> collection)
 {
     return collection.DeleteManyAsync("{}", _cancellationTokenSource.Token);
 }
コード例 #23
0
        public async Task DeleteEntitiesAsync(List <string> ids)
        {
            var filter = Builders <T> .Filter.In("_id", ids);

            await mongoCollection.DeleteManyAsync(filter);
        }
コード例 #24
0
        public async Task <bool> DeleteAllPlayers()
        {
            var delete = await _collectionPlayers.DeleteManyAsync("{}");

            return(true);
        }
コード例 #25
0
 /// <summary>
 /// 根据条件删除
 /// </summary>
 public static void Delete(Expression <Func <User, bool> > predicate)
 {
     collection.DeleteManyAsync(predicate);
 }
コード例 #26
0
 private Task ClearData(IMongoCollection <BsonDocument> collection)
 {
     return(collection.DeleteManyAsync("{}", _cancellationTokenSource.Token));
 }
コード例 #27
0
        public virtual async Task <bool> DeleteAsync(Expression <Func <T, bool> > filter)
        {
            DeleteResult actionResult = await _collection.DeleteManyAsync(filter);

            return(actionResult.IsAcknowledged && actionResult.DeletedCount > 0);
        }
コード例 #28
0
 private async Task InitializeCollectionAsync(IMongoCollection<BsonDocument> collection, List<BsonDocument> documents)
 {
     await collection.DeleteManyAsync(new BsonDocument());
     if (documents.Count > 0)
     {
         await collection.InsertManyAsync(documents);
     }
 }
コード例 #29
0
 public Task DeleteManyAsync(Expression <Func <T, bool> > filterExpression)
 {
     return(Task.Run(() => _collection.DeleteManyAsync(filterExpression)));
 }
コード例 #30
0
 public static IMongoCollection <T> Delete <T>(this IMongoCollection <T> collection, Expression <Func <T, bool> > filter) where T : TDocument
 {
     collection.DeleteManyAsync <T>(filter);
     return(collection);
 }
コード例 #31
0
 public Task <DeleteResult> DeleteManyAsync(FilterDefinition <T> filter, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(_Repository.DeleteManyAsync(filter, cancellationToken));
 }
コード例 #32
0
 /// <summary>
 /// Deletes all configs for a project
 /// </summary>
 /// <param name="projectId">Project id</param>
 /// <returns>Task</returns>
 public async Task DeleteConfigsForProject(string projectId)
 {
     await _ConfigCollection.DeleteManyAsync(p => p.ProjectId == projectId);
 }