How to remove obsolete fields in Mongo?

I removed some fields from the document definition. I want to delete this field for all documents in the collection. How can i do this?

+43
mongodb
Dec 27 '11 at 5:01
source share
2 answers

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 from which it was deleted.

The general update command has the form db.collection.update( criteria, objNew, upsert, multi ) . The returned false and true arguments turn off the upsert mode and activate multiple updates so that the request updates all documents in the collection (and not just the first match).

Update for MongoDB 2.2 +

Now you can 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 ) 
+112
Dec 27 '11 at 17:24
source share

just do something like that

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

oooh the answer $unset that someone gave with update() here is also very cool.

+29
Dec 27 '11 at 5:07
source share



All Articles