I know how to remove field from collection:
db.example.update({},{$unset: {field_to_del:1}},false,true)
But I want to delete all document fields where the length is zero when updating document.
I think you could approach this one of two ways:
1) Know in your app which fields have been removed and remove them on update as you do in your question.
2) Script it as a batch job. This probably does what you need: It forcibly removes any empty field (that is, empty string value) in any document in a collection (collection 'so' in this case)
var updateEmptyField = function(o){
for (var f in o){
if (o[f] === ''){
eval ("db.so.update({},{$unset: {" + f + ":1}},false,true);");
}
}
}
db.so.find().forEach(updateEmptyField);
You need to use eval here to use the variable holding the field name.