How to Use $set and $unset Operators in MongoDB
Last Updated :
10 Feb, 2025
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 |
---|
Purpose | Adds or updates a field in a document. | Removes a field from a document. |
Operation Type | Modify or insert fields. | Delete fields. |
Effect on Existing Data | Updates existing values or adds new fields. | Removes the specified field if it exists. |
Handling Non-Existent Fields | Adds the field if it does not exist. | Ignores the operation if the field does not exist. |
Example | db.collection.updateOne({ _id: 1 }, { $set: { name: "John" } }) | db.collection.updateOne({ _id: 1 }, { $unset: { name: "" } }) |
Common Use Case | Updating 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
Similar Reads
How to Use $unwind Operator in MongoDB?
MongoDB $unwind operator is an essential tool for handling arrays within documents. It helps deconstruct arrays, converting each array element into a separate document, which simplifies querying, filtering, and aggregation in MongoDB. By understanding the MongoDB $unwind syntax users can utilize thi
6 min read
Using $search and Compound Operators in MongoDB
In MongoDB, advanced querying techniques allow users to efficiently manage and retrieve data. The $search operator is a powerful tool for performing text searches within collections while compound operators like $and, $or, and $nor enable the creation of complex queries by combining multiple conditi
5 min read
MongoDB Query and Projection Operator
MongoDB query operators play a crucial role in interacting with data stored in MongoDB collections. Similar to SQL, these operators enable users to filter, compare, and manipulate data efficiently. Query operators allow for value-based comparisons, logical evaluations, and array operations, making d
11 min read
MongoDB - $setOnInsert Operator
The $setOnInsert operator in MongoDB is a powerful tool used in updating operations with the upsert option. It allows us to specify values that should be set only when a new document is inserted. In this article, we will learn about the $setOnInsert Operator in MongoDB in detail and so on. MongoDB $
4 min read
How to use the $lookup operator in aggregation pipelines in MongoDB?
One of the essential stages of the Aggregation Pipeline is the $lookup. It enables us to accomplish a left outer join between two collections. This step is quite beneficial when we have to compose data from different collections into a single document. The Aggregation Pipeline in MongoDB is a robust
4 min read
MongoDB AND operator ( $and )
MongoDB, a popular NoSQL database, offers several powerful query operators, including the $and operator. This operator enables us to combine multiple conditions in a query to retrieve documents that satisfy all of the specified conditions. The $and operator is a critical tool for building complex, p
4 min read
How to Perform Aggregation Operations in MongoDB using Node.js?
Aggregation operations in MongoDB allow you to process data records and return computed results. These operations group values from multiple documents, and perform a variety of operations on the grouped data to return a single result. MongoDB's aggregation framework is powerful and flexible, enablin
3 min read
How to Update Objects in a Document's Array in MongoDB?
In the area of MongoDB, managing a database with a large collection of documents can be challenging especially when it comes to updating specific objects within arrays of nested objects. This scenario is common in NoSQL databases like MongoDB. In this article, weâll explore some methods for updating
5 min read
How to set the document value type in MongoDB using Node.js?
Mongoose.module is one of the most powerful external module of the node.js. Mongoose is a MongoDB ODM i.e (Object database Modelling) that used to translate the code and its representation from MongoDB to the Node.js server. Mongoose module provides several functions in order to manipulate the docum
2 min read
MongoDB - Field Update Operators
MongoDB offers a range of powerful field update operators that enable efficient modification of specific fields within documents. These operators allow developers to update specific fields in documents without rewriting the entire document, thus improving performance and operational efficiency. By g
5 min read