MongoDB: How do I remove a field from every document?

MongoDB allows you to remove a field from every document in a collection by using the $unset operator to specify the field to be removed. This operation can be performed in the MongoDB shell or using the MongoDB drivers in your programming language. To remove a field from every document in a collection, you need to specify the name of the field to be removed and the collection on which the operation should be performed. The $unset operator will then remove the specified field from each document in the collection.


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 .

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

x