Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update many documents using UpdateManyAsync

I have the following method to update a document in MongoDB:

public async Task UpdateAsync(T entity)
{
    await _collection.ReplaceOneAsync(filter => filter.Id == entity.Id, entity);
}

Which works fine - I was just wondering if anybody has an example of how the UpdateManyAsync function works:

public async Task UpdateManyAsync(IEnumerable<T> entities)
{
    await _collection.UpdateManyAsync(); // What are the parameters here
}

Any advice is appreciated!

like image 834
TomSelleck Avatar asked Jul 05 '18 14:07

TomSelleck


1 Answers

UpdateOneAsync works the same way as update with multi: true in Mongo shell. So you can specify filtering condition and update operation and it will affect multiple documents. For instance to increment all a fields where a is greater than 10 you can use this method:

var builder = Builders<SampleClass>.Update;
await myCollection.UpdateManyAsync(x => x.a > 10, builder.Inc(x => x.a, 1));

I guess you'd like to replace multiple documents. That can be achieved using bulkWrite method. If you need generic method in C# then you can introduce some kind of marker interface to build filter part of replace operation:

public interface IMongoIdentity
{
    ObjectId Id { get; set; }
}

Then you can add generic constaint to your class and use BuikWrite in .NET like below:

class YourRepository<T> where T : IMongoIdentity
{
    IMongoCollection<T> collection;

    public async Task UpdateManyAsync(IEnumerable<T> entities)
    {
        var updates = new List<WriteModel<T>>();
        var filterBuilder = Builders<T>.Filter;

        foreach (var doc in entities)
        {
            var filter = filterBuilder.Where(x => x.Id == doc.Id);
            updates.Add(new ReplaceOneModel<T>(filter, doc));
        }

        await collection.BulkWriteAsync(updates);
    }
}
like image 127
mickl Avatar answered Oct 20 '22 04:10

mickl