45

I have removed some fields from document definition. I want to remove this field across all documents of collection. How can I do it?

Alexey Zakharov
  • 24,694
  • 42
  • 126
  • 197
  • 3
    See [this highly related question](http://stackoverflow.com/questions/4987289/how-to-remove-column-from-child-collection) – Cameron Dec 27 '11 at 05:06

2 Answers2

116

Try:

db.collection.update(
    { '<field>': { '$exists': true } },  // Query
    { '$unset': { '<field>': true  } },  // Update
    false,                               // Upsert
    true                                 // Multi-update
)

where field is your deprecated field and collection is the collection it was removed from.

The general update command is of the form db.collection.update( criteria, objNew, upsert, multi ). The false and true trailing arguments disable upsert mode and enable multi update so that the query updates all of the documents in the collection (not just the first match).

Update for MongoDB 2.2+

You can now provide a JSON object instead of positional arguments for upsert and multi.

db.collection.update(
    { '<field>': { '$exists': true } },  // Query
    { '$unset': { '<field>': true  } },  // Update
    { 'multi': true }                    // Options
)
Tyler Brock
  • 29,626
  • 15
  • 79
  • 79
  • 3
    The value of specified for the value of the field in the $unset statement (i.e. 1 here) does not impact the operation. [$unset operator](http://docs.mongodb.org/manual/reference/operator/unset/#_S_unset) – Xiao Jan 14 '13 at 10:24
29

just do something like this

db.people.find().forEach(function(x) {
   delete x.badField;
   db.people.save(x);
})

oooh the $unset answer someone gave using update() here is pretty awesome too.

Community
  • 1
  • 1
Jamund Ferguson
  • 16,721
  • 3
  • 42
  • 50
  • Thx, Jamund. Your approach works too. – Alexey Zakharov Dec 29 '11 at 08:33
  • Cannot accept 2 answers. So just upvoted it. – Alexey Zakharov Dec 29 '11 at 08:34
  • 3
    Don't do it this way. This method will be extremely slow for large collections because it processes each item individually running multiple queries for each item. – Tyler Brock Jan 14 '13 at 15:52
  • 5
    This is useful pattern, but only when you need to do non-trivial updates that may require a complex processing of each of the documents. – Timothy055 Mar 04 '13 at 16:20
  • 1
    This is also useful for when the $unset version is setting the field to null, and you want to remove the field completely. – Ben Taitelbaum Jul 24 '14 at 16:33
  • 1
    Very useful since setting `x.badField = null;` doesn't wipe the field during save like my library does - it actually saves NULL – Nic Cottrell Feb 21 '15 at 20:15
  • Still works in MongoDB version 2.6.1. Further, was able to update another field at the same time: `db.people.find().forEach(function(x) { delete x.badField; x.fieldToChange = "new value"; db.people.save(x); })` – leanne Nov 29 '15 at 17:47