Skip to content

Instantly share code, notes, and snippets.

@vendettamit
Created December 4, 2019 22:14
Show Gist options
  • Save vendettamit/132b406e3565c5d27bc009cbf44b3758 to your computer and use it in GitHub Desktop.
Save vendettamit/132b406e3565c5d27bc009cbf44b3758 to your computer and use it in GitHub Desktop.
Update All fields of a document in MongoDB using BuildWrite
public async Task<long> UpdateBulk<T>(IMongoCollection<T> _collection, IEnumerable<T> items, FilterDefinition<T> filter, params string[] propertiesToSkip)
{
if (!items.Any())
{
return 0;
}
var updates = new List<WriteModel<T>>();
var filterBuilder = Builders<T>.Filter;
var updater = Builders<T>.Update;
var requests = new List<UpdateOneModel<T>>();
var updateValues = new List<UpdateDefinition<T>>();
foreach (var doc in items)
{
foreach (PropertyInfo prop in typeof(Case).GetProperties())
{
if (prop.Name == "Id" || propertiesToSkip.Contains(prop.Name, StringComparer.InvariantCultureIgnoreCase)) continue;
//Create field update definition
updateValues.Add(updater.Set(prop.Name, prop.GetValue(doc)));
}
// Convert all field udpates definitions to single model update request
var request = new UpdateOneModel<T>(filter, updater.Combine(updateValues));
request.IsUpsert = true;
requests.Add(request);
}
updates.AddRange(requests);
BulkWriteResult result = await _collection.BulkWriteAsync(updates);
long updatedCount = result.ModifiedCount;
Log.Info("Updated {updatedCount} documents.", updatedCount);
return updatedCount;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment