updateOne and $set

updateOne() changes one document. It takes two arguments. The first is a filter that chooses the document. The second says what to change:

db.movies.updateOne(
  { title: "Dunkirk" },
  { $set: { rating: 7.9 } }
)
db.movies.findOne(
  { _id: 7 },
  { _id: 0, title: 1, rating: 1 }
)

Output:

{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}
{ title: 'Dunkirk', rating: 7.9 }

$set is an update operator. It sets the fields you list and leaves every other field as it was. Dunkirk keeps its title, year, votes and genres.

Read the report. matchedCount: 1 means the filter found one document. modifiedCount: 1 means one document was changed. These two numbers can be different. If the document already had a rating of 7.9, it would be matched but not modified.

If the filter finds nothing, you do not get an error. The update does nothing, and the report shows it:

db.movies.updateOne(
  { title: "Tenet" },
  { $set: { rating: 7.4 } }
)

Output:

{
  acknowledged: true,
  insertedId: null,
  matchedCount: 0,
  modifiedCount: 0,
  upsertedCount: 0
}

There is no movie called Tenet, so matchedCount is 0. When an update must happen, check matchedCount in the report.

$set can also add a field that a document does not have yet:

db.movies.updateOne(
  { _id: 3 },
  { $set: { oscars: 4 } }
)
db.movies.findOne(
  { _id: 3 },
  { _id: 0, title: 1, oscars: 1 }
)

Output:

{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}
{ title: 'Parasite', oscars: 4 }

Parasite now has an oscars field, and no other movie has one.

updateOne changes only the first document that matches, even if the filter matches several. The next lesson shows how to change many documents at once.

In the exercise, change La La Land's rating to 8.1.