1

I am building out a method in C# using the mongodb driver in which I need to update multiple documents. The trick is that for some documents I want to remove a value from an array property and in other documents I want to add the value if it doesn't already exist in the same array property. I know I can build two separate filter definitions and update definitions and then call the UpdateMany twice. Is there any way to compose both sets of filters and update definitions and execute them at once? Each filter definition is built from a unique list of documents. Please note the snippet below. My goal is to combine both the add and remove updates if possible.

var removePermRecords = updatePermissions.Where(x => x.IsAuthorized == false).Select(x => x.Id);
var filterRemove = Builders<Record>.Filter.In(x => x.Id, removePermRecords);
var updateRemove = Builders<Record>.Update.Pull("userIds", userId);
var removeUpdateResult = MongoContext.UpdateMany(filterRemove, updateRemove);

var addPermRecords = updatePermissions.Where(x => x.IsAuthorized == true).Select(x => x.Id);
var filterAdd = Builders<Record>.Filter.In(x => x.Id, addPermRecords)
var updateAdd = Builders<Record>.Update.AddToSet("userIds", userId);
var addUpdateResult = MongoContext.UpdateMany(filterAdd, updateAdd);
user95488
  • 129
  • 2
  • 11
  • It seems to be impossible, since in an update document we cannot use `$cond`, but please provide a simple example and we'll see. – cbartosiak Oct 23 '17 at 21:51
  • You use the "Bulk: API methods. Preferably with the wrapping [`BulkWrite`](http://mongodb.github.io/mongo-csharp-driver/2.4/apidocs/html/M_MongoDB_Driver_IMongoCollection_1_BulkWrite.htm) method in modern drivers. "Bulk API" methods are how you submit "multiple" operations in a "single" request and response. – Neil Lunn Oct 24 '17 at 00:40

0 Answers0