Recently I’ve been working on adding SignalR to a web application, and that means broadcasting records to clients after they’ve been updated. I could make different methods for each update type and react accordingly, but I’m pretty lazy so I decided to just make one “update” method that receives the entire record (and replaces it on the client side).
Mongo
The documents are stored in Mongo, so we’re using the .NET driver.
UpdateOneAsync
UpdateOneAsync takes in a FilterDefinition and an UpdateDefinition. Mongo will then use the filter to find the first matching record and apply the update.
This works just fine to update the record, but Mongo doesn’t return the record to you – just an UpdateResult that defines the status of the action (number of records affected, etc). It would be a lot easier to just return the updated record so that we can send it to our SignalR clients.
FindOneAndUpdateAsync
FindOneAndUpdateAsync does almost the same thing as UpdateOneAsync, but it will find, update, and return the entire record.
Note one gotcha – by default, it will return the document before the update is applied. If you want the document after the update is applied, you need to specify an FindOneAndUpdateOptions object and set the ReturnDocument field.