In MongoDB, upsert is a feature that allows you to update a document if it exists or insert a new document if it doesn’t exist. The term "upsert" is a combination of the words "update" and "insert". This feature is particularly useful when you are working with data that may or may not already exist in your database, and you don’t know whether you need to perform an update or an insert.
The syntax for an upsert operation in MongoDB is as follows:
db.collection.update(
<query>,
<update>,
{
upsert: <boolean>,
...
}
)
The ‘<query>‘ parameter specifies the document or documents that you want to update or insert. If the document already exists in the collection, the ‘<update>‘ parameter specifies how you want to modify the existing document, similar to a regular ‘update()‘ operation. If the document does not exist in the collection, the ‘<update>‘ parameter specifies the document to be inserted.
The ‘upsert‘ option is what makes this operation an upsert. If it is set to ‘true‘, MongoDB will insert the document specified in ‘<update>‘ if no documents match the ‘<query>‘ parameter. If it is set to ‘false‘ (the default), MongoDB will not insert a new document if no documents match the ‘<query>‘ parameter.
Here is an example of how to use an upsert operation in MongoDB. First, let’s assume that we have a collection called ‘users‘, which stores documents representing user accounts. Each document has an ‘_id‘ field, which is a unique identifier for the user account. If the user account corresponding to a given ‘_id‘ already exists in the collection, we want to update it with new information. If the user account does not exist, we want to create a new one with the given ‘_id‘:
// Update or create a user account with the given _id
const userId = '123';
db.users.update(
{ _id: userId },
{ $set: { email: 'john@example.com', name: 'John' } },
{ upsert: true }
);
In this example, we are updating or creating a user account with the ‘_id‘ ‘123‘. The ‘email‘ and ‘name‘ fields are set to new values. If a user account with the ‘_id‘ ‘123‘ already exists in the ‘users‘ collection, its ‘email‘ and ‘name‘ fields will be updated with the new values. If no user account with the ‘_id‘ ‘123‘ exists in the collection, a new document will be inserted with the given ‘_id‘, ‘email‘, and ‘name‘ fields.