w3resource

Remove a Field from MongoDB Document with $unset Operator

How to remove a field from a MongoDB Document?

To completely remove a field from a MongoDB document, you can use the $unset operator. This operator permanently deletes the specified field from all matched documents in the collection. Removing fields from documents is useful when you no longer need a particular field, want to save storage space, or clean up outdated data.

In MongoDB, deleting a field entirely from a document can be accomplished with the $unset operator. This operator removes the field from the document, making it as if the field never existed. You can apply this to one or multiple fields as needed. Use this operation when you want to remove unnecessary fields from your database documents without impacting the rest of the document data.

Syntax:

The syntax to remove a field from a MongoDB document is:

db.<collection>.updateOne(
  { <filter_conditions> },
  { $unset: { <field_to_remove>: "" } }
)

Explanation:

  • <collection>: The collection where you are performing the update.
  • <filter_conditions>: The conditions to match documents (e.g., { _id: <document_id> }).
  • <field_to_remove>: The name of the field you want to remove.

Example:

Suppose you have a products collection and you want to delete the discount field from a document where the _id is a specific value.

Code:

// Completely remove the 'discount' field from a specific document
db.products.updateOne(
  { _id: ObjectId("64a8c1a5f0d7e7b3c2a3b4f7") }, // Filter to find the document
  { $unset: { discount: "" } }                   // Remove 'discount' field
)

Explanation:

  • db.products.updateOne(...)
    This method targets the products collection and applies the $unset operation to a single document that matches the specified filter conditions.
  • { _id: ObjectId(...) }
    This is the filter condition to locate the document by its _id. This filter ensures that only the intended document is modified.
  • { $unset: { discount: "" } }
    The $unset operator permanently deletes the discount field from the document. Setting the field to "" is a convention, as MongoDB only requires the field name (not the value) to perform the unset operation.

This operation completely removes the discount field from the document, and it will no longer appear in future queries on the products collection.

Practical Guides to MongoDB Snippets and Examples.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/mongodb/snippets/how-to-remove-a-field-from-a-mongodb-dcument.php