MongoDB: How to Remove a Field from Every Document


You can use the following methods to remove fields from every document in a collection in MongoDB:

Method 1: Remove One Field

db.collection.updateMany({}, {$unset: {"field1":1}})

Method 2: Remove Multiple Fields

db.collection.updateMany({}, {$unset: {"field1":1, "field2":1}})

The following examples show how to use each method with a collection teams with the following documents:

db.teams.insertOne({team: "Mavs", position: "Guard", points: 31})
db.teams.insertOne({team: "Spurs", position: "Guard", points: 22})
db.teams.insertOne({team: "Rockets", position: "Center", points: 19})

Example 1: Remove One Field

We can use the following code to remove the “points” field from every document in our collection:

db.teams.updateMany({}, {$unset: {"points":1}})

We can then use the following query to view each document in our collection:

db.teams.find()

This query returns the following results:

{ _id: ObjectId("61893b7196cd2ba58ce928f4"),
  team: 'Mavs',
  position: 'Guard' }

{ _id: ObjectId("61893b7196cd2ba58ce928f5"),
  team: 'Spurs',
  position: 'Guard' }

{ _id: ObjectId("61893b7196cd2ba58ce928f6"),
  team: 'Rockets',
  position: 'Center' }

Notice that the “points” field has been removed from every document.

Example 2: Remove Multiple Fields

We can use the following code to remove the “points” and “position” field from every document in our collection:

db.teams.updateMany({}, {$unset: {"points":1, "position":1}})

We can then use the following query to view each document in our collection:

db.teams.find()

This query returns the following results:

{ _id: ObjectId("61893bf896cd2ba58ce928f7"), team: 'Mavs' }
{ _id: ObjectId("61893bf896cd2ba58ce928f8"), team: 'Spurs' }
{ _id: ObjectId("61893bf896cd2ba58ce928f9"), team: 'Rockets' }

Notice that the “points” and “position” fields have been removed from every document.

Note: You can find the complete documentation for $unset here.

Additional Resources

The following tutorials explain how to perform other common operations in MongoDB:

MongoDB: How to Add a New Field in a Collection
MongoDB: How to Group By and Count
MongoDB: How to Group By Multiple Fields

Leave a Reply

Your email address will not be published.