How to use $unset Operator In MongoDB
The $unset operator is used to remove a specific field from a MongoDB document. It takes the field name as its argument and removes that field completely from the document. This method is useful when you want to remove a single field from a document.
Example: Let say, we want to remove the department field from an employee document with a specific _id.
db.Employee.update
(
{ _id: ObjectId("65f8b8499abfc382ebcd9668") },
{ $unset: { department: "" } }
)
Output:
Explanation:
- The update operation targets the document with the specified _id.
- The $unset operator removes the department field completely from the document.
- Upon successful execution, the department field will be removed from the targeted employee document.
How to Remove a Field Completely From a MongoDB Document?
In MongoDB, managing data is flexible and efficient, allowing developers to adapt to evolving application requirements easily. One common operation is removing fields from documents.
Whether it’s to Organize our data structure, improve performance or change business needs, MongoDB provides straightforward methods to achieve this task.
In this article, we’ll explore how to remove a field completely from a MongoDB document with the help of an example.