From the course: MongoDB C# Developer Associate Cert Prep

Unlock this course with a free trial

Join today to access over 24,900 courses taught by industry experts.

Updating MongoDB documents by using findAndModify()

Updating MongoDB documents by using findAndModify() - MongoDB Tutorial

From the course: MongoDB C# Developer Associate Cert Prep

Updating MongoDB documents by using findAndModify()

- Welcome. In this video you'll learn how to update and return the same document in MongoDB. We'll cover how and when to use the findAndModify() method. We'll also explain how findAndModify() is different from the updateOne() method. findAndModify() is used to return the document that has just been updated. For example, imagine we're creating an app that tracks the number of users who download a podcast. One way to update and return the number of downloads is to use the updateOne() and findOne() methods. First, we would use updateOne() to increment the downloads field. Then we would use findOne() to return the document by using the _id. The problem with this approach is that it makes two round trips to the server where findAndModify() is only one. Additionally, if we make our update via updateOne(), another user could modify the document before our findOne() and we'll get a different version of the document. To…

Contents