Bobcares

MongoDB’s `$set` and `$unset` Operators: A Practical Guide

PDF Header PDF Footer

Learn more about MongoDB’s `$set` and `$unset` operators. Our MongoDB Support team is ready to assist with any queries or concerns.

MongoDB’s `$set` and `$unset` Operators: A Practical Guide

MongoDB offers developers flexible tools to modify and manage documents within collections. Two of the most frequently used operators for document updates are `$set` and `$unset`. These operators make it easy to add, update, or remove specific fields without having to rewrite the entire document.

Today, we will explore how the `$set` and `$unset` operators work, along with real-world examples to help us use them effectively in our MongoDB applications.

About the `$set` Operator

The MongoDB `$set` operator lets us add new fields or update existing ones in a document. Unlike some update operations that overwrite the entire document, `$set` only modifies the specified fields, leaving all other data untouched. This makes it a useful tool for incremental updates.

If you’re working with MongoDB documents, you might also find it helpful to learn how to generate ObjectIds manually. This is particularly useful when creating new documents programmatically.

Some of the key features of `$set` include:

MongoDB’s `$set` and `$unset` Operators: A Practical Guide

  • If the field we specify doesn’t exist, `$set` will create it and assign the provided value.
  • If the field already exists, `$set` replaces its current value.
  • Fields not mentioned in the `$set` operation remain unchanged.
  • We can use `$set` to update nested objects or elements within arrays.

Here is the syntax of the $set operator :

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

Example 1. Adding a New Field
Imagine you have a `users` collection with the following document:

{ "_id": 1, "name": "John", "age": 32 }Copy Code

Suppose you want to add a `city` field without affecting the existing data. Here’s how:


db.users.updateOne(
{ _id: 1 },
{ $set: { city: "London" } }
);
Copy Code

Output:

{ "_id": 1, "name": "John", "age": 32, "city": "London" }Copy Code

Since the `city` field didn’t exist, MongoDB added it using `$set`. This is a common approach when adding new attributes to user profiles or product entries dynamically.

Example 2. Updating an Existing Field
Let’s update John’s age from 32 to 34:


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

Output:

{ "_id": 1, "name": "John", "age": 34, "city": "London" }Copy Code

Here, `$set` replaced the `age` value without affecting the `name` or `city` fields. This makes it ideal for updating user details, such as changing phone numbers, email addresses, or profile information.

If you often work with MongoDB arrays and need to add unique items to sets, check out this guide on using $group and $addToSet in MongoDB aggregations. It’s a great complement to using $set when handling grouped data.

About the `$unset` Operator

While `$set` helps us add or modify data, the MongoDB `$unset` operator lets us remove fields entirely from a document. If the field exists, `$unset` deletes it. If it doesn’t exist, the operation is simply ignored.

Here are the key features of `$unset`:

  • Deletes only the specified fields.
  • The rest of the document remains unchanged.
  • If the field doesn’t exist, `$unset` has no effect.
  • We can remove multiple fields in a single operation.
  • It is perfect for removing obsolete, deprecated, or temporary fields.

Here is the syntax of the $unset operator :

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

Example 1. Removing an Existing Field
Let’s remove the `city` field from John’s document:


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

Output:

{ "_id": 1, "name": "John", "age": 34 }Copy Code

The `city` field is now gone from the document. This is useful when cleaning up records or optimizing storage by eliminating unnecessary fields.

Example 2. Attempting to Remove a Non-Existent Field
Suppose we try to remove a field that doesn’t exist, such as `nonExistentField`:

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

Output:

{ "_id": 1, "name": "John", "age": 34 }Copy Code

Since `nonExistentField` wasn’t present, MongoDB simply ignores the `$unset` operation. No error is raised, and the document remains unchanged. This behavior helps prevent unintended disruptions during data cleanup tasks.
If you’re new to MongoDB aggregations, here’s a helpful tutorial on using MongoDB aggregate functions with Node.js and npm.

Additionally, if you want to ensure your aggregation pipelines are optimized, you can use the explain() method to analyze performance. Learn more about interpreting aggregate() with execution stats here.

[Need assistance with a different issue? Our team is available 24/7.]

Conclusion

Together, the $set and  $unset operators enable efficient data manipulation while maintaining the integrity and flexibility of our database.

In short, our Support Engineers introduced us to MongoDB’s `$set` and `$unset` operators.

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

Get featured on the Bobcares blog and share your expertise with a global tech audience.

WRITE FOR US
server management

Spend time on your business, not on your servers.

TALK TO US

Or click here to learn more.

Speed issues driving customers away?
We’ve got your back!