4

Normally you would use the following to remove a field from a collection. However the code below does not work for empty ("") fields. How would you go about deleting an empty field in MongoDB?

db.collection.update({}, {$unset: {"": ""}}, {multi:true})

I get the following error message when I try this:

WriteResult({
    "nMatched" : 0,
    "nUpserted" : 0,
    "nModified" : 0,
    "writeError" : {
        "code" : 56,
        "errmsg" : "An empty update path is not valid."
    }
})
Community
  • 1
  • 1
Jonathan
  • 8,453
  • 9
  • 51
  • 74

4 Answers4

5

It looks like empty string keys must only be partially supported by MongoDB.

This isn't as efficient as a multi-update, but it does work to remove those fields in the shell:

db.collection.find().forEach(function(doc) {
    delete doc[''];
    db.collection.save(doc);
});
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
5

To do this using the update or updateMany method, you must specify the parameter you want to update, such as name:

db.collection.updateMany({name: ""}, { $unset : { name : 1 }})
J.C. Gras
  • 4,934
  • 1
  • 37
  • 44
2

If you need to delete rows with the field, that is empty, you can use:

db.collection.deleteMany({ 'myField': null})
Roman
  • 19,236
  • 15
  • 93
  • 97
0

Updated for mongodb version 4.2+ (db.collection.save is no longer supported)

Empty field keys aren't fully supported by mongodb, and look like they are going to be depreciated.

To get rid of empty field keys

db.collection.find({"":{$exists:true}).forEach(
    (doc)=>{
       delete doc[""];  
       db.collection.replaceOne(doc,doc,{upsert:true})
})
I.Blair
  • 481
  • 3
  • 7