2

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
  • 7,966
  • 7
  • 51
  • 67

3 Answers3

3

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
  • 290,447
  • 61
  • 595
  • 453
3

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,149
  • 1
  • 34
  • 40
2

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

db.collection.deleteMany({ 'myField': null})
Roman
  • 15,278
  • 11
  • 75
  • 80