Upsert: Update, Or Insert If Missing
Sometimes you want to save a document, but you do not know if it exists yet. If it exists, you want to update it. If it does not, you want to create it. This is called an upsert (update + insert).
There is no movie with _id 9. A normal updateOne would match nothing and do nothing. With the option { upsert: true }, it creates the document instead:
db.movies.updateOne(
{ _id: 9 },
{ $set: { title: "Dune", year: 2021 } },
{ upsert: true }
)
Output:
{
acknowledged: true,
insertedId: 9,
matchedCount: 0,
modifiedCount: 0,
upsertedCount: 1
}
The report shows matchedCount: 0 and upsertedCount: 1. Nothing matched, so MongoDB inserted a new document. It used _id: 9 from the filter and the fields from $set.
Now run an upsert on the same _id again:
db.movies.updateOne(
{ _id: 9 },
{ $set: { rating: 8 } },
{ upsert: true }
)
db.movies.findOne({ _id: 9 })
Output:
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
{ _id: 9, title: 'Dune', year: 2021, rating: 8 }
This time the document exists, so it was updated: matchedCount: 1 and upsertedCount: 0. The final document has the fields from both calls.
Upsert is useful when you copy data from another system, or when you save a total that may not exist yet. One statement works in both cases, and you do not need to check first. The upsert option goes in the third argument, and updateMany accepts it too.
In the exercise, save the movie Arrival on _id 9, which does not exist yet.