Feature Request: FindManyAndUpdateAsync

Right now, with the C# mongodb driver, you can utilize FindOneAndUpdateAsync. This is a very useful method as a parameter, you can set:

new FindOneAndUpdateOptions<BsonDocument, T>
{
    ReturnDocument = ReturnDocument.After
}

This allows for a single call to the database (maybe not behind the scenes?) that updates the document that matches the filter and returns the updated document after it has been updated.

I would like to do the same thing but while updating multiple documents. I have read the suggestion to do multiple calls to update by filter, then get by filter. This works for most cases, except when you update a property (or properties) that are in the filter. In that case, you lose the connection to the documents that were updated.

Hi, Steven,

Thank you for your suggestion. FindOneAndUpdateAsync in the .NET/C# Driver is a wrapper around the underlying MongoDB command findAndModify. This command explicitly states:

The findAndModify command modifies and returns a single document.

Thus this is a limitation of MongoDB and not the .NET/C# Driver per se. To update multiple documents, you can use UpdateManyAsync, which wraps the update command (with the multi:true option specified). As you note you would have to re-query the documents after the update and handle the case where another update happened between the UpdateManyAsync and FindAsync commands.

One of the features that findAndModify provides is the atomic nature of the update and query. When you specify new: true (e.g. ReturnDocument.After), you are guaranteed to receive the results of the updated document without any intervening writes. This is very useful for writing persistent locks and semaphores.

Hopefully this explains the distinction between FindOneAndUpdateAsync versus UpdateManyAsync. To support FindManyandUpdateAsync, the server would first need to implement support for findAndModifyMany. You can submit this feature request via the MongoDB Feedback Engine.

Sincerely,
James

2 Likes

Hey James,

Thank you for explaining the distinctions and for pointing out that this is more of a mongodb engine suggestion than a driver suggestion as it needs to exist there first.

The more I thought about this, the more I realized that FindManyAndUpdateAsync may not be a great idea. With it needing to be atomic, the possibility of large quantities could drastically hurt performances. I think, at least for now, UpdateManyAsync returning the number of documents updated will suffice for me.

Much appreciated,

Steven

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.