Steps to Use Upsert in MongoDB
1).Open the MongoDB Shell using mongosh.
2).Select the database using use database_name.
3).Use updateOne() or updateMany() with the upsert: true option.
4).If a matching document exists, MongoDB updates it.
5).If no matching document exists, MongoDB inserts a new document.
6).Verify the result using find().
Example:
use studentdb
db.students.updateOne(
{ name: "John" },
{ $set: { age: 20, course: "MongoDB" } },
{ upsert: true }
)
db.students.find()