How to remove deprecated fields in Mongo? [closed]

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


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
)

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.