Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing empty fields from MongoDB

Tags:

mongodb

nosql

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."
    }
})
like image 456
Jonathan Avatar asked Nov 01 '25 15:11

Jonathan


1 Answers

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);
});
like image 100
JohnnyHK Avatar answered Nov 04 '25 11:11

JohnnyHK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!