Introduction
Deleting fields with $unset

Imagine you need to delete the related_comics field from all documents in the comic_books collection. Here's how you can do that using the $unset operator:

use comic_book_store_db

// Delete the "related_comics" field from all documents
db.comic_books.updateMany(
  {},
  { $unset: { related_comics: "" } }
)

In this snippet, we first switch to the comic_book_store_db database using the use command. We then call the updateMany method on the comic_books collection to update all documents within it. The empty {} object specifies that the update should apply to every document. The $unset operator, followed by { related_comics: "" }, removes the related_comics field from all documents in the collection, effectively cleaning up the dataset by deleting this field.

Renaming fields with $rename

Now that you know how to remove fields, let's see how you can rename them. In the example below, you rename the published_year field to year_published:

use comic_book_store_db

// Rename the "published_year" field to "year_published"
db.comic_books.updateMany(
  {},
  { $rename: { "published_year": "year_published" } }
)

In this snippet, we switch to the comic_book_store_db database and call the updateMany method again. The empty {} selector ensures that all documents are targeted. The $rename operator with { "published_year": "year_published" } specifies that the field published_year should be renamed to year_published. This not only makes the field name more descriptive but also ensures consistency across your data schema.

Removing and Renaming Nested Fields
Summary
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal