Open In App

How to Use $set and $unset Operators in MongoDB

Last Updated : 10 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

MongoDB is a NoSQL database that stores data in documents instead of traditional rows and columns found in relational databases. These documents, grouped into collections, allow for flexible data storage and retrieval. One of MongoDB’s key advantages is its ability to dynamically update documents using update operators. Among these, two crucial operators for field manipulation are $set and $unset

In this article, we will explain their syntax, use cases, and practical examples. Understanding how to use these operators effectively enhances database operations and improves data integrity

MongoDB $set Operator

The $set operator is one of MongoDB’s most commonly used update operators, allowing developers to add new fields or modify existing ones in a document. This operator provides flexibility by ensuring that updates are performed seamlessly, without altering other fields in the document.

Unlike some other update operations, $set does not overwrite the entire document—it only modifies the specified fields while keeping the rest of the document intact. This makes it highly useful for incremental updates, ensuring data integrity and efficiency.

Key Features of the $set Operator:

  • Adds new fields if they don’t exist: If a specified field is missing in a document, $set will create it and assign the given value.
  • Updates existing fields: If the field already exists, its value will be replaced with the new one provided in the $set operation.
  • Does not affect other fields: The $set operation ensures that only the specified fields are modified, leaving the rest of the document unchanged.
  • Supports nested field updates: $set can be used to update nested objects or arrays within a document.

Syntax:

{ $set: { <field1>: <value1>, <field2>: <value2> } }

Key Terms:

  • If the specified field exists, $set updates its value.
  • If the field does not exist, $set creates it and assigns the given value.

Example 1: Adding a New Field

In this example, we have a users collection where each document represents a user with basic details such as _id, name, and age. The goal is to add a new field, city, to the document using the $set operator without modifying existing fields.

Initial Document in the users Collection:

{ "_id": 1, "name": "Alice", "age": 25 }

Query:

db.users.updateOne(
{ _id: 1 },
{ $set: { city: "New York" } }
);

Output:

{ "_id": 1, "name": "Alice", "age": 25, "city": "New York" }

Explanation: Since the city field did not exist, $set added it to the document. This is useful when adding new attributes to a user profile dynamically.

Example 2: Updating an Existing Field

In this example, we use the $set operator to update an existing field in the users collection. The document already contains an age field with a value of 25, and we modify it to 26 without affecting any other fields in the document.

Query:

db.users.updateOne(
{ _id: 1 },
{ $set: { age: 26 } }
);

Output:

{ "_id": 1, "name": "Alice", "age": 26, "city": "New York" }

Explanation: The age field already existed, so $set updated its value. This is particularly useful in scenarios where we need to modify user details, such as updating phone numbers or email addresses.

MongoDB &unset Operator

The $unset operator is used to remove a specified field from a document in MongoDB. Unlike $set, which modifies or adds a field, $unset completely deletes the field from the document. If the specified field does not exist, the operation has no effect, ensuring that only existing fields are removed without causing errors. This operator is particularly useful for data cleanup and removing obsolete attributes from documents.

Key Features of $unset Operator

  • Removes a Field Completely$unset deletes the specified field from a document instead of updating its value.
  • Non-Destructive to Other Fields – Only the targeted field is removed, leaving the rest of the document unchanged.
  • No Effect if Field Doesn’t Exist – If the specified field is not present, $unset does nothing, preventing unnecessary operations.
  • Useful for Data Cleanup – Helps in removing outdated, deprecated, or unnecessary fields from documents.
  • Can Remove Multiple Fields – Supports deleting multiple fields in a single operation by specifying them in the $unset query.

Syntax:

{ $unset: { <field1>: "", <field2>: "" } }

Key Terms:

  • If the field exists, $unset removes it.
  • If the field does not exist, $unset has no effect.

Example 1: Removing an Existing Field

In this example, the updateOne operation attempts to remove a field called nonExistentField from the document with _id: 1. Since this field does not exist, MongoDB ignores the $unset operation and leaves the document unchanged. No error is raised, and the operation completes silently.

Query:

db.users.updateOne(
{ _id: 1 },
{ $unset: { city: "" } }
);

Output:

{ "_id": 1, "name": "Alice", "age": 26 }

Explanation: The city field was removed from the document. This is helpful when a field is no longer required and needs to be removed to optimize storage.

Example 2: Attempting to Remove a Non-Existent Field

In this example, the updateOne operation attempts to remove the nonExistentField from the document with _id: 1. Since nonExistentField does not exist in the document, MongoDB ignores the $unset operation. The document remains unaffected, and no error is raised.

Query:

db.users.updateOne(
{ _id: 1 },
{ $unset: { nonExistentField: "" } }
);

Output:

{ "_id": 1, "name": "Alice", "age": 26 }

Explanation: Since nonExistentField wasn’t present, $unset had no effect. This ensures that unnecessary database operations are not performed when attempting to remove non-existent fields.

Comparing $set and $unset

Given below is a comparison table for MongoDB's $set and $unset operators:

Feature$set$unset
PurposeAdds or updates a field in a document.Removes a field from a document.
Operation TypeModify or insert fields.Delete fields.
Effect on Existing DataUpdates existing values or adds new fields.Removes the specified field if it exists.
Handling Non-Existent FieldsAdds the field if it does not exist.Ignores the operation if the field does not exist.
Exampledb.collection.updateOne({ _id: 1 }, { $set: { name: "John" } })db.collection.updateOne({ _id: 1 }, { $unset: { name: "" } })
Common Use CaseUpdating or adding new data to a document.Removing unnecessary or obsolete fields.

Best Practices for Using $set and $unset

  • Use $set sparingly for frequently changing fields to avoid unnecessary updates.
  • Use $unset when cleaning up documents to remove redundant data.
  • Perform batch updates when possible to optimize performance.
  • Ensure field updates are necessary before using $set to avoid bloating documents.

Conclusion

The $set and $unset operators are essential tools for modifying MongoDB documents. While $set helps add or update fields, $unset efficiently removes unwanted fields. Understanding their use cases ensures a structured and optimized NoSQL database. By using these operators effectively, developers can maintain clean, structured, and performant databases, leading to better application performance and scalability. By mastering the use of $set and $unset, developers can easily manage document structure and keep their MongoDB databases flexible and well-organized


Next Article
Article Tags :

Similar Reads