public async Task <BulkWriteResult <TModel> > BulkWriteAsync( IEnumerable <WriteModel <TModel> > requests, BulkWriteOptions options = null, CancellationToken token = default) { try { return(await _collection.BulkWriteAsync(requests, options, token)); } catch (MongoAuthenticationException mongoAuthEx) { throw new NautilusMongoDbException("Mongo security error", mongoAuthEx); } catch (MongoConnectionException mongoConnectEx) { throw new NautilusMongoDbException(mongoConnectEx.Message, mongoConnectEx); } catch (MongoWriteException mongoWriteEx) { throw new NautilusMongoDbException("Mongo write error", mongoWriteEx); } catch (MongoCommandException mongoCmdEx) { throw new NautilusMongoDbException("Mongo command error", mongoCmdEx); } catch (TimeoutException timeoutEx) { throw new NautilusMongoDbException("Mongo has timed out", timeoutEx); } catch (Exception ex) { throw new NautilusMongoDbException("Mongo throws a general exception", ex); } }
private static async Task Copy(IMongoCollection <BsonDocument> inColl, IMongoCollection <BsonDocument> outColl, int batch, HashSet <BsonValue> outIds) { var models = new List <ReplaceOneModel <BsonDocument> >(); foreach (var doc in inColl.Find(d => true).ToEnumerable()) { var id = doc[_idName]; var idFilter = Builders <BsonDocument> .Filter.Eq(_idName, id); var replace = new ReplaceOneModel <BsonDocument>(idFilter, doc); replace.IsUpsert = true; models.Add(replace); outIds.Remove(id); if (models.Count == batch) { Console.WriteLine("Writing " + models.Count + " document(s)."); await outColl.BulkWriteAsync(models).ConfigureAwait(false); models.Clear(); } } if (models.Count > 0) { Console.WriteLine("Writing " + models.Count + " document(s)."); await outColl.BulkWriteAsync(models).ConfigureAwait(false); } }
public virtual void AddMany(IEnumerable <T> entities) { var options = new BulkWriteOptions { IsOrdered = false, BypassDocumentValidation = false }; _collection.BulkWriteAsync((IEnumerable <WriteModel <T> >)entities, options); }
public Task <BulkWriteResult <T> > BulkWriteAsync( IEnumerable <WriteModel <T> > requests, BulkWriteOptions?options = null, CancellationToken cancellationToken = default ) { return(collection.BulkWriteAsync(requests, options, cancellationToken)); }
static async Task Main(string[] args) { Setup(); List <ReplaceOneModel <Movie> > operations = new List <ReplaceOneModel <Movie> >(); Console.WriteLine("Starting the data migration."); var datePipelineResults = TransformDatePipeline(); Console.WriteLine($"I found {datePipelineResults.Count} docs where the lastupdated field is of type 'string'."); if (datePipelineResults.Count > 0) { BulkWriteResult <Movie> bulkWriteDatesResult = null; // TODO Ticket: Call _moviesCollection.BulkWriteAsync, passing in the // datePipelineResults. You will need to use a ReplaceOneModel<Movie> // (https://api.mongodb.com/csharp/current/html/T_MongoDB_Driver_ReplaceOneModel_1.htm). foreach (var item in datePipelineResults) { operations.Add(new ReplaceOneModel <Movie>(Builders <Movie> .Filter.Where(x => x.Id == item.Id), item)); } bulkWriteDatesResult = await _moviesCollection.BulkWriteAsync(operations, new BulkWriteOptions { IsOrdered = false }); Console.WriteLine($"{bulkWriteDatesResult.ProcessedRequests.Count} records updated."); } var ratingPipelineResults = TransformRatingPipeline(); Console.WriteLine($"I found {ratingPipelineResults.Count} docs where the imdb.rating field is not a number type."); if (ratingPipelineResults.Count > 0) { BulkWriteResult <Movie> bulkWriteRatingsResult = null; // TODO Ticket: Call _moviesCollection.BulkWriteAsync, passing in the // ratingPipelineResults. You will need to use a ReplaceOneModel<Movie> // (https://api.mongodb.com/csharp/current/html/T_MongoDB_Driver_ReplaceOneModel_1.htm). foreach (var item in ratingPipelineResults) { operations.Add(new ReplaceOneModel <Movie>(Builders <Movie> .Filter.Where(x => x.Id == item.Id), item)); } bulkWriteRatingsResult = await _moviesCollection.BulkWriteAsync(operations, new BulkWriteOptions { IsOrdered = false }); Console.WriteLine($"{bulkWriteRatingsResult.ProcessedRequests.Count} records updated."); } Console.WriteLine(); Console.WriteLine("Checking the data conversions..."); Verify(); // Keep the console window open until user hits `enter` or closes. Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Press <Enter> to close."); Console.ReadLine(); }
static async Task Main(string[] args) { Setup(); Console.WriteLine("Starting the data migration."); var datePipelineResults = TransformDatePipeline(); Console.WriteLine($"I found {datePipelineResults.Count} docs where the lastupdated field is of type 'string'."); if (datePipelineResults.Count > 0) { BulkWriteResult <Movie> bulkWriteDatesResult = null; // TODO Ticket: Call _moviesCollection.BulkWriteAsync, passing in the // datePipelineResults. You will need to use a ReplaceOneModel<Movie> // (https://api.mongodb.com/csharp/current/html/T_MongoDB_Driver_ReplaceOneModel_1.htm). // var updates = datePipelineResults.Select(d => { return(new ReplaceOneModel <Movie>(GetMovieFilter(d.Id), d)); }); bulkWriteDatesResult = await _moviesCollection.BulkWriteAsync(updates); Console.WriteLine($"{bulkWriteDatesResult.ProcessedRequests.Count} records updated."); } var ratingPipelineResults = TransformRatingPipeline(); Console.WriteLine($"I found {ratingPipelineResults.Count} docs where the imdb.rating field is not a number type."); if (ratingPipelineResults.Count > 0) { BulkWriteResult <Movie> bulkWriteRatingsResult = null; // TODO Ticket: Call _moviesCollection.BulkWriteAsync, passing in the // ratingPipelineResults. You will need to use a ReplaceOneModel<Movie> // (https://api.mongodb.com/csharp/current/html/T_MongoDB_Driver_ReplaceOneModel_1.htm). // var updates = ratingPipelineResults.Select(r => { return(new ReplaceOneModel <Movie>(GetMovieFilter(r.Id), r)); }); bulkWriteRatingsResult = await _moviesCollection.BulkWriteAsync(updates); Console.WriteLine($"{bulkWriteRatingsResult.ProcessedRequests.Count} records updated."); } Console.WriteLine(); Console.WriteLine("Checking the data conversions..."); Verify(); // Keep the console window open until user hits `enter` or closes. Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Press <Enter> to close."); Console.ReadLine(); }
public async Task <long> SaveAllAsync(IEnumerable <WebhookPublisher> models, bool?references = true, CancellationToken token = default) { var saves = 0; using (var scope = TransactionScopeOption.Required.AsTransactionScopeFlow()) { var keys = new List <Guid>(); var candidates = new List <WebhookPublisher>(); foreach (var model in models) { var candidate = model; if (!references.HasValue || !references.Value) { candidate = model.CreateCopy(); candidate.Definitions.Clear(); } candidates.Add(candidate); keys.Add(candidate.Id); } var matches = await FindAllByKeysAsync(keys, references : references, token : token); var similar = candidates.Intersect(matches); var different = matches.Any() ? candidates.Except(matches) : candidates; if (similar.Any()) { var requests = new List <WriteModel <WebhookPublisher> >(); foreach (var model in similar) { token.ThrowIfCancellationRequested(); requests.Add(new ReplaceOneModel <WebhookPublisher>(Builders <WebhookPublisher> .Filter.Where(x => x.Id == model.Id), model)); } var result = await collection.BulkWriteAsync(requests, cancellationToken : token); saves += result.IsAcknowledged ? (int)result.MatchedCount : 0; } if (different.Any()) { var requests = new List <WriteModel <WebhookPublisher> >(); foreach (var model in different) { token.ThrowIfCancellationRequested(); requests.Add(new InsertOneModel <WebhookPublisher>(model)); } var result = await collection.BulkWriteAsync(requests, cancellationToken : token); saves += result.IsAcknowledged ? (int)result.InsertedCount : 0; } scope.Complete(); } return(saves); }
public Task <BulkWriteResult <T> > BulkWriteAsync( IEnumerable <WriteModel <T> > requests, BulkWriteOptions?options = null, CancellationToken cancellationToken = default) { if (TryGetSession(out IClientSessionHandle? session)) { return(BulkWriteAsync(session, requests, options, cancellationToken)); } return(_collection.BulkWriteAsync(requests, options, cancellationToken)); }
public async Task <long> SaveAllAsync(IEnumerable <WebhookDefinition> models, bool?references = true, CancellationToken token = default) { var count = 0L; using (var scope = TransactionScopeOption.Required.AsTransactionScopeFlow()) { var keys = new List <Guid>(); foreach (var model in models) { keys.Add(model.Id); } var matches = await FindAllByKeysAsync(keys, references : references, token : token); var similar = Enumerable.Empty <WebhookDefinition>(); var different = Enumerable.Empty <WebhookDefinition>(); if (matches.Any()) { similar = models.Intersect(matches); different = models.Except(matches); } if (similar.Any()) { var requests = new List <WriteModel <WebhookDefinition> >(); foreach (var model in similar) { token.ThrowIfCancellationRequested(); requests.Add(new ReplaceOneModel <WebhookDefinition>(Builders <WebhookDefinition> .Filter.Where(x => x.Id == model.Id), model)); } var result = await collection.BulkWriteAsync(requests, cancellationToken : token); count += result.IsAcknowledged ? result.MatchedCount : 0L; } if (different.Any()) { var requests = new List <WriteModel <WebhookDefinition> >(); foreach (var model in different) { token.ThrowIfCancellationRequested(); requests.Add(new InsertOneModel <WebhookDefinition>(model)); } var result = await collection.BulkWriteAsync(requests, cancellationToken : token); count += result.IsAcknowledged ? result.InsertedCount : 0L; } scope.Complete(); } return(count); }
public Task UpdateAsync(IEnumerable <LoggedUser> users, CancellationToken cancellationToken = default) { var updates = users.Select(x => { var filter = Builders <LoggedUser> .Filter.Eq(f => f.Identifier, x.Identifier); var update = Builders <LoggedUser> .Update .Set(s => s.ChatIdentifier, x.ChatIdentifier) .Set(s => s.FirstName, x.FirstName) .Set(s => s.Password, x.Password) .Set(s => s.Salt, x.Salt); return(new UpdateOneModel <LoggedUser>(filter, update)); }).ToList(); return(_users.BulkWriteAsync(updates, null, cancellationToken)); }
public async Task ReplaceManyAsync(ICollection <TDocument> documents, CancellationToken cancellationToken = default) { var writeModels = new List <WriteModel <TDocument> >(); foreach (var doc in documents) { var filter = Builders <TDocument> .Filter.Eq(doc => doc.Id, doc.Id); var writeModel = new ReplaceOneModel <TDocument>(filter, doc); writeModels.Add(writeModel); } await Collection.BulkWriteAsync(writeModels, new BulkWriteOptions(), cancellationToken); }
private async Task PopulateCategory(CancellationToken cancellationToken) { _logger?.LogDebug("Populating Category in existing events..."); var fb = Builders <RecordedEventDocument> .Filter; var cursor = await _events .Find(fb.Not(fb.Exists(e => e.Category))) .ToCursorAsync(cancellationToken); var batch = new List <WriteModel <RecordedEventDocument> >(); while (await cursor.MoveNextAsync(cancellationToken)) { batch.Clear(); foreach (var document in cursor.Current) { var category = _streamNameResolver.AggregateName(document.Stream); var definition = new UpdateOneModel <RecordedEventDocument>( Builders <RecordedEventDocument> .Filter.Where(e => e.Id == document.Id), Builders <RecordedEventDocument> .Update.Set(e => e.Category, category) ); batch.Add(definition); } if (batch.Count > 0) { await _events.BulkWriteAsync(batch, null, cancellationToken); } } }
async Task ICatalogDb <string, TFilterQuery, TData> .AddAsync(IEnumerable <TData> items) { foreach (var batch in items.Batch(10000)) { await _mols.BulkWriteAsync(batch.Select(i => new InsertOneModel <TData>(i))); } }
public async Task HandleAsync(TeamRoleDeletedEvent @event, CancellationToken cancellationToken) { var users = await _usersCollection.Find(t => t.Teams.Any(r => r.Id == @event.TeamId)) .ToListAsync(cancellationToken); var requests = new List <WriteModel <User> >(); foreach (var user in users) { var userRole = await _teamsCollection.Find(t => t.Id == @event.TeamId) .Project(t => t.Roles.Single(r => r.Name.ToLower() == DefaultRoles.User.Name.ToLower() && r.IsDefault)) .SingleAsync(cancellationToken); var team = user.Teams.Single(t => t.Id == @event.TeamId); team.Role.Name = userRole.Name; team.Role.Permissions = userRole.Permissions; var filter = Builders <User> .Filter.Where(m => m.Id == user.Id); var pullUpdate = Builders <User> .Update.PullFilter(m => m.Teams, t => t.Id == @event.TeamId); var pushUpdate = Builders <User> .Update.Push(m => m.Teams, team); requests.Add(new UpdateOneModel <User>(filter, pullUpdate)); requests.Add(new UpdateOneModel <User>(filter, pushUpdate)); } await _usersCollection.BulkWriteAsync(requests, cancellationToken : cancellationToken); }
public async Task HandleAsync(AuthenticatedUserUpdatedEvent @event, CancellationToken cancellationToken) { var requests = new List <WriteModel <Team> >(); var authenticatedUserId = _authenticatedUserAccessor.AuthenticatedUser.Id; if (!_authenticatedUserAccessor.AuthenticatedUser.Teams.Any()) { return; } foreach (var teamId in _authenticatedUserAccessor.AuthenticatedUser.Teams.Select(t => t.Id)) { var member = new Member { Name = @event.Name, EmailAddress = @event.EmailAddress }; var filter = Builders <Team> .Filter.Where(t => t.Id == teamId); var pullUpdate = Builders <Team> .Update.PullFilter(t => t.Members, t => t.Id == authenticatedUserId); var pushUpdate = Builders <Team> .Update.Push(t => t.Members, member); requests.Add(new UpdateOneModel <Team>(filter, pullUpdate)); requests.Add(new UpdateOneModel <Team>(filter, pushUpdate)); } await _teamsCollection.BulkWriteAsync(requests, cancellationToken : cancellationToken); }
public async Task WriteGameSummaries(IReadOnlyCollection <GameUpdate> updates) { await _games.BulkWriteAsync(updates.Select(update => { var filter = Builders <Game> .Filter.Eq(x => x.Id, update.GameId); var model = Builders <Game> .Update .SetOnInsert(x => x.Id, update.GameId) .Set(x => x.Season, update.Payload["season"].AsInt32) .Set(x => x.Day, update.Payload["day"].AsInt32) .Set(x => x.LastUpdate, update.Payload) .Max(x => x.LastUpdateTime, update.FirstSeen); if (update.Payload["gameStart"].AsBoolean) { model = model.Min(x => x.Start, update.FirstSeen); } if (update.Payload["gameComplete"].AsBoolean) { model = model.Min(x => x.End, update.LastSeen); } return(new UpdateOneModel <Game>(filter, model) { IsUpsert = true }); })); }
private async Task <long> CreateReadingDefinitions( IMongoCollection <ReadingDefinition> collection, string clientId, List <ReadingDefinition> definitions, CancellationToken cancellationToken) { var filterBuilder = Builders <ReadingDefinition> .Filter; var filter = filterBuilder.Eq(definition => definition.ClientId, clientId); var createModels = new List <InsertOneModel <ReadingDefinition> >(); foreach (var definition in definitions) { var model = new InsertOneModel <ReadingDefinition>(definition); createModels.Add(model); } var options = new BulkWriteOptions() { BypassDocumentValidation = false, IsOrdered = false }; try { var result = await collection.BulkWriteAsync(createModels, options, cancellationToken); return(result.ModifiedCount); } catch (Exception e) { throw new Exception("Failed to create definitions", e); } }
private async Task <long> ReplaceDocumentsByClientId <T>( IMongoCollection <T> collection, FilterDefinition <T> clientIdFilter, List <T> documents, CancellationToken cancellationToken) where T : IClientEntity { var updateModels = new List <WriteModel <T> >(); foreach (var document in documents) { var model = new ReplaceOneModel <T>(clientIdFilter, document); updateModels.Add(model); } var options = new BulkWriteOptions() { BypassDocumentValidation = false, IsOrdered = false }; try { var result = await collection.BulkWriteAsync(updateModels, options, cancellationToken); return(result.ModifiedCount); } catch (Exception e) { throw new Exception("Failed to update readings", e); } }
public virtual async Task <long> ReplaceMany(IEnumerable <T> entities, bool isUpsert, CancellationToken token = default) { if (entities.Count() == 0) { return(0); } var requests = new List <WriteModel <T> >(); Func <object, object> idGetter = FieldDefinitions.GetIdFieldGetter(typeof(T)); foreach (T entity in entities) { ObjectId entityId = (ObjectId)idGetter.Invoke(entity); var filter = Builders <T> .Filter.Eq("_id", entityId); requests.Add(new ReplaceOneModel <T>(filter, entity) { IsUpsert = isUpsert }); } // BulkWrite var options = new BulkWriteOptions() { IsOrdered = false }; BulkWriteResult <T> bulkResult = await _collection .BulkWriteAsync(requests, options, cancellationToken : token) .ConfigureAwait(false); return(bulkResult.Upserts.Count + bulkResult.ModifiedCount); }
/// <summary> /// The InsertRangeAsync. /// </summary> /// <param name="entities">The entities<see cref="IEnumerable{TEntity}"/>.</param> /// <returns>The <see cref="Task"/>.</returns> public virtual async Task InsertRangeAsync(IEnumerable <TEntity> entities) { var options = new BulkWriteOptions { IsOrdered = false, BypassDocumentValidation = false }; var result = (await _collection.BulkWriteAsync((IEnumerable <WriteModel <TEntity> >)entities, options)).IsAcknowledged; }
public async Task UpdateManyAsync(List <TEntity> objList) { List <WriteModel <TEntity> > bulkOps = new List <WriteModel <TEntity> >(); foreach (var obj in objList) { if (obj.Id == BsonObjectId.Empty) { var insertOne = new InsertOneModel <TEntity>(obj); bulkOps.Add(insertOne); } else { var upsertOne = new ReplaceOneModel <TEntity>(Builders <TEntity> .Filter.Where(x => x.Id == obj.Id), obj) { IsUpsert = true }; bulkOps.Add(upsertOne); } } if (bulkOps.Count > 0) { await _collection.BulkWriteAsync(bulkOps); } }
public async Task <bool> SaveOrUpdateManyAsync(IEnumerable <AvgCost> avgCosts) { var bulkList = new List <WriteModel <AvgCost> >(avgCosts.Count()); foreach (var avgCost in avgCosts) { var updDef = new UpdateDefinitionBuilder <AvgCost>() .SetOnInsert(x => x.Customer, avgCost.Customer) .SetOnInsert(x => x.Symbol, avgCost.Symbol) .Set(x => x.Price, avgCost.Price) .Set(x => x.Quantity, avgCost.Quantity) .PushEach(x => x.History, avgCost.History); var filterBuilder = Builders <AvgCost> .Filter; var filterDef = filterBuilder.And(filterBuilder.Eq(x => x.Customer, avgCost.Customer), filterBuilder.Eq(x => x.Symbol, avgCost.Symbol)); bulkList.Add(new UpdateOneModel <AvgCost>(filterDef, updDef) { IsUpsert = true }); } var result = await _collection.BulkWriteAsync(bulkList); return(result.IsAcknowledged); }
public async Task ApplyAsync(string bucket, IEnumerable <DocumentRecord> records) { var filterBuilder = new FilterDefinitionBuilder <BsonDocument>(); var filter = FilterByBucketName(bucket); var bulkOperation = new List <WriteModel <BsonDocument> >(); foreach (var record in records) { var bytes = record.Read(); var doc = BsonSerializer.Deserialize <BsonDocument>(bytes); var docId = filterBuilder.And(filter, filterBuilder.Eq(e => e["_id"], Guid.Parse(record.Key))); var model = new ReplaceOneModel <BsonDocument>(docId, doc) { IsUpsert = true }; bulkOperation.Add(model); } await _projectionCollection.BulkWriteAsync(bulkOperation).ConfigureAwait(false); }
public async Task HandleAsync(TeamRoleUpdatedEvent @event, CancellationToken cancellationToken) { var members = await _usersCollection.Find(t => t.Teams.Any(r => r.Id == @event.TeamId)) .ToListAsync(cancellationToken); var requests = new List <WriteModel <User> >(); foreach (var member in members) { var team = member.Teams.Single(t => t.Id == @event.TeamId); team.Role.Name = @event.Name; team.Role.Permissions = @event.Permissions.ToDataPermissions(); var filter = Builders <User> .Filter.Where(m => m.Id == member.Id); var pullUpdate = Builders <User> .Update.PullFilter(m => m.Teams, t => t.Id == @event.TeamId); var pushUpdate = Builders <User> .Update.Push(m => m.Teams, team); requests.Add(new UpdateOneModel <User>(filter, pullUpdate)); requests.Add(new UpdateOneModel <User>(filter, pushUpdate)); } await _usersCollection.BulkWriteAsync(requests, cancellationToken : cancellationToken); }
public override async Task <BulkWriteResult <BsonDocument> > ApplyToField(IFieldDefinition field, IMongoCollection <BsonDocument> collection, CancellationToken?cancellationToken = null) { if (cancellationToken == null) { cancellationToken = CancellationToken.None; } var updateModels = new WriteModel <BsonDocument> [field.Extras.Extra.Count]; int iModel = 0; var dummies = field.Extras.Extra; foreach (var column in dummies) { var query = Builders <BsonDocument> .Filter.And( Builders <BsonDocument> .Filter.Eq(field.Name, column.Value) ); var updates = new List <UpdateDefinition <BsonDocument> >(); updates.Add(Builders <BsonDocument> .Update.Set(field.Name, column.Key)); var qrUpdateRoot = Builders <BsonDocument> .Update.Combine(updates); var actionModel = new UpdateManyModel <BsonDocument>(query, qrUpdateRoot); updateModels[iModel++] = actionModel; } var result = await collection.BulkWriteAsync(updateModels, new BulkWriteOptions() { }, cancellationToken.Value); return(result); }
public async Task BulkUpdate(List <Product> productsToUpdate) { try { var models = new List <WriteModel <ProductDTO> >(); foreach (var product in productsToUpdate) { var filter = new ExpressionFilterDefinition <ProductDTO>(p => p.ProductId == product.ProductId); var updateDefinitionList = new List <UpdateDefinition <ProductDTO> > { new UpdateDefinitionBuilder <ProductDTO>().Set(p => p.AvailableQuantity, product.AvailableQuantity), new UpdateDefinitionBuilder <ProductDTO>().Set(p => p.ReservedQuantity, product.ReservedQuantity) }; var action = new UpdateOneModel <ProductDTO>(filter, Builders <ProductDTO> .Update.Combine(updateDefinitionList)); models.Add(action); } await _collection.BulkWriteAsync(models); } catch (Exception e) { _logger.LogError(e, $"Error trying to access mongo, method: {nameof(IMongoCollection<Order>.BulkWriteAsync)}"); throw; } }
/// <summary> /// Creates a <see cref="ReplaceOneModel{T}"/> for each entity and calls /// <see cref="IMongoCollection{T}.BulkWriteAsync"/> as an upsert. /// </summary> /// <typeparam name="T">The type of <see cref="IEntity"/>.</typeparam> /// <param name="collection">The collection.</param> /// <param name="entities">The entities to insert or update.</param> /// <returns>The entities ids.</returns> /// <exception cref="ArgumentNullException">Thrown when the given <paramref name="entities"/> is null.</exception> public static async Task <IEnumerable <Guid> > AddOrUpdateMany <T>(this IMongoCollection <T> collection, ICollection <T> entities) where T : class, IEntity { Guard.AgainstNullArgument(nameof(collection), collection); Guard.AgainstNullArgument(nameof(entities), entities); if (!entities.Any()) { return(new List <Guid>()); } var operations = new List <ReplaceOneModel <T> >(); foreach (var entity in entities) { entity.SetId(); var filter = Builders <T> .Filter.Eq(x => x.Id, entity.Id); var operation = new ReplaceOneModel <T>(filter, entity) { IsUpsert = true }; operations.Add(operation); } await collection.BulkWriteAsync(operations); return(entities.Select(e => e.Id)); }
public async Task HandleAsync(TeamUpdatedEvent @event, CancellationToken cancellationToken) { var memberIds = await _teamsCollection.Find(t => t.Id == @event.TeamId) .Project(t => t.Members.Select(m => m.Id).ToList()) .SingleOrDefaultAsync(cancellationToken); var team = _authenticatedUserAccessor.AuthenticatedUser.Teams .Single(t => t.Id == @event.TeamId); team.Name = @event.Name; var filter = Builders <User> .Filter.Where(m => memberIds.Contains(m.Id)); var pullUpdate = Builders <User> .Update.PullFilter(m => m.Teams, t => t.Id == team.Id); var pushUpdate = Builders <User> .Update.Push(m => m.Teams, team); var requests = new[] { new UpdateOneModel <User>(filter, pullUpdate), new UpdateOneModel <User>(filter, pushUpdate) }; await _usersCollection.BulkWriteAsync(requests, cancellationToken : cancellationToken); }
public Task InsertOrReplaceBatchAsync(T[] entities) { return(_collection.BulkWriteAsync(entities.Select(d => new ReplaceOneModel <T>(new FilterDefinitionBuilder <T>().Eq(x => x.BsonId, d.BsonId), d) { IsUpsert = true }))); }
public virtual async Task <bool> AddRangeAsync(IEnumerable <T> entities) { var options = new BulkWriteOptions { IsOrdered = false, BypassDocumentValidation = false }; return((await Collection.BulkWriteAsync((IEnumerable <WriteModel <T> >)entities, options)).IsAcknowledged); }