[MongoDB] Command to Remove Fields

Tadashi Shigeoka ·  Mon, March 23, 2015

To remove unnecessary fields in MongoDB, use db.collection.update with $unset.

MongoDB

Data Preparation for $unset

First, insert verification data. This time we’ll register 3 new entries.

> db.users.insert( { name : 'test' , age : 20 } )
> db.users.insert( { name : 'hoge' , age : 50 } )
> db.users.insert( { name : 'spam' , age : 90 } )

> db.users.find()
{ "_id" : ObjectId("55102489395c0a2d41edd220"), "name" : "test", "age" : 20 }
{ "_id" : ObjectId("551024c0395c0a2d41edd221"), "name" : "hoge", "age" : 50 }
{ "_id" : ObjectId("551025fc395c0a2d41edd222"), "name" : "spam", "age" : 90 }

$unset for Single Document

To remove a field from a document with a specific _id, specify the condition in the first argument and set the fourth argument to false to only delete one entry.

> db.users.update( { _id : ObjectId( "55102489395c0a2d41edd220" ) } , { $unset : { age : 1 } } , false , false )
> db.users.find()
{ "_id" : ObjectId("55102489395c0a2d41edd220"), "name" : "test" }
{ "_id" : ObjectId("551024c0395c0a2d41edd221"), "name" : "hoge", "age" : 50 }
{ "_id" : ObjectId("551025fc395c0a2d41edd222"), "name" : "spam", "age" : 90 }

$unset for All Documents

To remove a specific field from all documents, specify {} in the first argument to target all documents, and set the fourth argument to true to target the field in all matching documents for deletion.

> db.users.update( { } , { $unset : { age : 1 } } , false , true )
> db.users.find()
{ "_id" : ObjectId("55102489395c0a2d41edd220"), "name" : "test" }
{ "_id" : ObjectId("551024c0395c0a2d41edd221"), "name" : "hoge" }
{ "_id" : ObjectId("551025fc395c0a2d41edd222"), "name" : "spam" }

Summary of $unset Usage

Finally, as a note of caution, the update method has the potential to blow away fields from all documents, so we want to avoid using it on production data as much as possible.

Reference Information

That’s all from the Gemba.